
package com.dmgis.qxfw.dataservice.businessservice.qxinfo.controller;


import com.dmgis.entity.DmGridInfo;
import com.dmgis.entity.DmMapPoint;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.DbConfig;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.Results;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.*;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.job_model;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.warning;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.base_product;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.summary_product;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.zy.thunder_fcst;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.*;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.*;
import com.dmgis.qxfw.dataservice.businessservice.common.service.IConfigService;
import com.dmgis.qxfw.dataservice.businessservice.common.util.*;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.FileRequestService;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.nyfw.service.IFarmIndexService;
import com.dmgis.qxfw.dataservice.businessservice.qxinfo.service.IGridDataService;
import com.dmgis.qxfw.dataservice.businessservice.qxinfo.service.IQxInfoService;
import com.dmgis.qxfw.dataservice.businessservice.qxinfo.service.IQxSmallScaleService;
import com.dmgis.qxfw.dataservice.businessservice.yyjt.service.IForecastInfoService;
import com.dmgis.qxfw.dataservice.businessservice.yysl.service.IWaternfoService;
import com.dmgis.qxfw.dataservice.gisservice.service.ITransformService;
import com.dmgis.qxfw.dataservice.pages.service.IComDisplayService;
import com.dmgis.weblib.GridAnalysis;
import com.dmgis.weblib.MapCommon;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.awt.image.BufferedImageGraphicsConfig;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.*;

/**
 * This class is used for 气象信息展示控制层
 *
 * @author dsq
 * @version 1.0, 2018年10月28日 下午12:29:00
 */
@Controller
@RequestMapping("/qxinfo")
public class QxForecastInfoController {
    private  final String operatingSystem;

    @Autowired
    public QxForecastInfoController(String operatingSystem) {
        this.operatingSystem = operatingSystem;
    }
    @Resource
    private IQxInfoService qxInfoService;
    @Autowired
    private IComDisplayService comDisplayService;

    @Resource
    private IForecastInfoService forecastInfoService;

    @Resource
    private IQxSmallScaleService skInfoService;

    @Resource
    private IFarmIndexService farmIndexService;

    @Resource
    private IWaternfoService waternfoService;

    @Resource
    private IGridDataService gridDataService;
    @Resource
    private IConfigService configService;

    @Resource
    private  ITransformService transformService;

    //MongoService1 ms = new MongoService1();
    FileRequestService ms = new FileRequestService();


    /**
     * 初始化城镇预报界面信息 1
     *
     */
    @RequestMapping("/initCZPage")
    @ResponseBody
    public Object initChengZhenPage() {
        ArrayList<Object> arrayList = new ArrayList<>();
        String type = "CITYTV";

        collectTime scaleNewDate = qxInfoService.getScaleNewDate(type);// 已修改
        StringBuilder dateTime = new StringBuilder();
        dateTime.append(scaleNewDate.getYear()+"-");
        dateTime.append(scaleNewDate.getMonth() + "-");
        dateTime.append(scaleNewDate.getDay()+" ");
        arrayList.add(dateTime.toString());
        arrayList.add(scaleNewDate.getHour());
        return arrayList;
    }

    /**
     * 初始化乡镇预报界面信息
     *
     * @author dsq 1
     * @date 2018年6月29日
     */
    @RequestMapping("/initXZPage")
    @ResponseBody
    public Object initXiangZhenPage() {
        ArrayList<Object> arrayList = new ArrayList<Object>();
        TownshipForecastKey newestDate = qxInfoService.getTownNewDate();
        // 获取yyyy-MM-dd HH:mm:ss 格式字符串
        String datechar = new DateTime(newestDate.getDateChar()).toDateTimeString();
        String[] dataLs = datechar.split(" ");
        //时次 时间
        arrayList.add(newestDate.getTimeChar());
        arrayList.add(dataLs[0]);
        arrayList.add(qxInfoService.getCityStation());
        return arrayList;
    }

    /*区划图-暴雪、暴雨、低温、冰雹、大风*/
    @RequestMapping("/getQuHuaTu")
    @ResponseBody
    public Object getQuHuaTu(HttpServletRequest request) {
        String typeName = request.getParameter("type");
        Object agrisrvList = farmIndexService.getQuHuaTu(typeName,request);
        return agrisrvList;
    }
/*大屏左侧城镇报信息*/
@RequestMapping("/ChenZhenBao")
@ResponseBody
public Object getChenZhenBao(HttpServletRequest request) {
    TownshipForecastKey selectKey = new TownshipForecastKey();// 查询类
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    // 获取当前时间
    Date date = new Date();
    // 获取 Calendar 实例并设置当前时间
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    // 获取调整后的 endTime
    String time = simpleDateFormat.format(calendar.getTime());
    calendar.setTime(date);
    // 设置当天的16:00:00时间
    calendar.set(Calendar.HOUR_OF_DAY, 16);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    // 获取当天16:00:00的时间
    Date sixteenOClock = calendar.getTime();
    // 获取当前时间
    Date currentDate = new Date();
    // 比较当前时间与当天16:00的时间
    String sc ="";
    if (currentDate.after(sixteenOClock)) {
        sc = "20";// 时次
    } else {
        sc = "08";// 时次
    }
    String sx = "24";// 时效
    String cityId = request.getParameter("cityId");//城市
    String type = "city";// 类型
    String county = request.getParameter("county");// 区市
    String strStationID = "";
    String strCountyName = "";
    int nTimes = 0;
    List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
    WebCtrlData wcd = new WebCtrlData();
    try {
        if (!StringUtil.IsNullOrEmpty(sx)) {
            nTimes = Integer.parseInt(sx);
        }
        if (!(cityId == null) && !cityId.equals("")) {
            selectKey.setStationID(cityId);// 站点号
        }
        selectKey.setNTimes(nTimes);
        selectKey.setTimeChar(sc);
        if (!StringUtil.IsNullOrEmpty(time)) {
            selectKey.setDateChar(DateTime.parseDate(time).toDate());
        }
        if (!StringUtil.IsNullOrEmpty(type) && type.equals("town")) {
            List<TownshipForecast> fcstList = qxInfoService.getTownshipFcst(selectKey, county);
            int count = fcstList.toArray().length;
            for (int i = 0; i < count; i += 2) {
                strStationID = fcstList.get(i).getStationID();
                strCountyName = fcstList.get(i).getStationName();
                if (type.equals("town")) {
                    if (strCountyName.contains("乡")) {
                        strCountyName = strCountyName.substring(0, strCountyName.indexOf('乡') + 1);
                    }
                    if (strCountyName.contains("镇")) {
                        strCountyName = strCountyName.substring(0, strCountyName.indexOf('镇') + 1);
                    }
                }
                String weather = "";// 天气信息
                String windD = "";// 风向信息
                String windV = "";// 风速信息
                String windS = "";// 风速信息
                String windD12 = WebCtrlData.GetAllFx(fcstList.get(i).getWindD().toString().replace("-65535", "0").trim());
                String windD24 = WebCtrlData.GetAllFx(fcstList.get(i + 1).getWindD().toString().replace("-65535", "0").trim());
                String windV12 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWindS())));
                String windV24 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i + 1).getWindS())));
                String windS12 = String.valueOf(fcstList.get(i).getWindS());
                String windS24 = String.valueOf(fcstList.get(i + 1).getWindS());
                if (windD12.equals(windD24)) {
                    windD += windD12;
                } else {
                    windD += windD12 + "转" + windD24;
                }
                if (windV12.equals(windV24)) {
                    windV += windV12;
                } else {
                    windV += windV12 + "~" + windV24;
                }
                if (windS12.equals(windS24)) {
                    windS += windS12 + "m/s";
                } else {
                    windS += windS12 + "~" + windS24 + "m/s";
                }
                if (fcstList.get(i).getWeather1().trim().equals(fcstList.get(i + 1).getWeather1().trim())) {
                    weather += wcd.GetWeatherTq(String.format("%02d",
                            Integer.parseInt(fcstList.get(i).getWeather1().toString().trim())));
                } else {
                    weather += wcd
                            .GetWeatherTq(String.format("%02d",
                                    Integer.parseInt(fcstList.get(i).getWeather1().toString().trim())))
                            + "转" + wcd.GetWeatherTq(String.format("%02d",
                            Integer.parseInt(fcstList.get(i+1).getWeather1().toString().trim())));
                }
                double maxTemp = fcstList.get(i + 1).getMaxTemp();
                double minTemp = fcstList.get(i + 1).getMinTemp();
                String pic1 = String.format("%02d",
                        Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather1())));
                String pic2 = String.format("%02d",
                        Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i + 1).getWeather1())));
                CityFcstInfo fcstInfo = new CityFcstInfo();
                fcstInfo.setStationId(strStationID);
                fcstInfo.setStationName(strCountyName);
                fcstInfo.setMinTemp(minTemp);
                fcstInfo.setMaxTemp(maxTemp);
                fcstInfo.setRain(fcstList.get(i).getRain());
                fcstInfo.setWindD(windD);
                fcstInfo.setWindV(windV);
                fcstInfo.setWindS(windS);
                fcstInfo.setPic1(pic1);
                fcstInfo.setPic2(pic2);
                fcstInfo.setLat(fcstList.get(i).getLatitude());
                fcstInfo.setLon(fcstList.get(i).getLongitude());
                DmMapPoint dt = transformService.LonLatConvertToLambert(fcstInfo.getLon(), fcstInfo.getLat());
                fcstInfo.setX(dt.x);
                fcstInfo.setY(dt.y);
                fcstInfo.setWeather1(fcstList.get(i).getWeather1().trim());
                fcstInfo.setWeather2(fcstList.get(i + 1).getWeather1().trim());
                fcstInfo.setWeather(weather);
                fcstInfo.setHumid(String.valueOf(fcstList.get(i).getHumid()) + "%");
                resultList.add(fcstInfo);
            }
        } else {
            List<ForecastInfo> fcstList = qxInfoService.getCityFcst(selectKey);
            int count = fcstList.toArray().length;
            for (int i = 0; i < count; i++) {
                strStationID = fcstList.get(i).getStationid();
                strCountyName = fcstList.get(i).getStationname();
                String weather = "";// 天气信息
                String windD = "";// 风向信息
                String windV = "";// 风速信息
                String windS = "";// 风速信息
                String windD12 = wcd.GetAllFx(fcstList.get(i).getWindd1().toString().replace("-65535", "0").trim());
                String windD24 = wcd.GetAllFx(fcstList.get(i).getWindd2().toString().replace("-65535", "0").trim());
                String windV12 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWind1())));
                String windV24 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWind2())));
                String windS12 = String.valueOf(fcstList.get(i).getWind1());
                String windS24 = String.valueOf(fcstList.get(i).getWind2());
                if (windD12.equals(windD24)) {
                    windD += windD12;
                } else {
                    windD += windD12 + "转" + windD24;
                }
                if (windV12.equals(windV24)) {
                    windV += windV12;
                } else {
                    windV += windV12 + "~" + windV24;
                }
                if (windS12.equals(windS24)) {
                    windS += windS12 + "m/s";
                } else {
                    windS += windS12 + "~" + windS24 + "m/s";
                }
                if (fcstList.get(i).getWeather1().toString().trim()
                        .equals(fcstList.get(i).getWeather2().toString().trim())) {
                    weather += wcd.GetWeatherTq(String.format("%02d",
                            Integer.parseInt(fcstList.get(i).getWeather1().toString().trim())));
                } else {
                    weather += wcd
                            .GetWeatherTq(String.format("%02d",
                                    Integer.parseInt(fcstList.get(i).getWeather1().toString().trim())))
                            + "转" + wcd.GetWeatherTq(String.format("%02d",
                            Integer.parseInt(fcstList.get(i).getWeather2().toString().trim())));
                }
                double maxTemp = Double.parseDouble(String.format("%.1f", fcstList.get(i).getMaxtemp()));
                double minTemp = Double.parseDouble(String.format("%.1f", fcstList.get(i).getMintemp()));
                String pic1 = String.format("%02d", Integer.parseInt(
                        WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather1().toString().trim())));
                String pic2 = String.format("%02d", Integer.parseInt(
                        WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather2().toString().trim())));
                CityFcstInfo fcstInfo = new CityFcstInfo();
                fcstInfo.setStationId(strStationID);
                fcstInfo.setStationName(strCountyName);
                fcstInfo.setMinTemp(minTemp);
                fcstInfo.setMaxTemp(maxTemp);
                fcstInfo.setRain(fcstList.get(i).getRain());
                fcstInfo.setWindD(windD);
                fcstInfo.setWindV(windV);
                fcstInfo.setWindS(windS);
                fcstInfo.setPic1(pic1);
                fcstInfo.setPic2(pic2);
                fcstInfo.setLat(fcstList.get(i).getLatitude());
                fcstInfo.setLon(fcstList.get(i).getLongitude());
                DmMapPoint dt = transformService.LonLatConvertToLambert(fcstInfo.getLon(), fcstInfo.getLat());
                fcstInfo.setX(dt.x);
                fcstInfo.setY(dt.y);
                fcstInfo.setWeather1(fcstList.get(i).getWeather1().toString().trim());
                fcstInfo.setWeather2(fcstList.get(i).getWeather2().toString().trim());
                fcstInfo.setWeather(weather);
                resultList.add(fcstInfo);
            }
        }
    } catch (Exception e) {
        // TODO: 城镇预报查询异常
        e.printStackTrace();
        // log.error(e);
    }
    return resultList;
}

    /**
     * 城镇预报查询
     */
    @RequestMapping("/ChenZhenYuBao")
    @ResponseBody
    public Object getCityFcst(HttpServletRequest request) {
        TownshipForecastKey selectKey = new TownshipForecastKey();// 查询类
        String time = request.getParameter("date");// 时间
        String sc = request.getParameter("sc");// 时次
        String sx = request.getParameter("sx");// 时效
        String cityId = request.getParameter("cityId");//城市
        String type = request.getParameter("type");// 类型
        String county = request.getParameter("county");// 区市
        String strStationID = "";
        String strCountyName = "";
        int nTimes = 0;
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        WebCtrlData wcd = new WebCtrlData();
        try {
            if (!StringUtil.IsNullOrEmpty(sx)) {
                nTimes = Integer.parseInt(sx);
            }
            if (!(cityId == null) && !cityId.equals("")) {
                selectKey.setStationID(cityId);// 站点号
            }
            selectKey.setNTimes(nTimes);
            selectKey.setTimeChar(sc);
            if (!StringUtil.IsNullOrEmpty(time)) {
                selectKey.setDateChar(DateTime.parseDate(time).toDate());
            }
            if (!StringUtil.IsNullOrEmpty(type) && type.equals("town")) {
                List<TownshipForecast> fcstList = qxInfoService.getTownshipFcst(selectKey, county);
                int count = fcstList.toArray().length;
                for (int i = 0; i < count; i += 2) {
                    strStationID = fcstList.get(i).getStationID();
                    strCountyName = fcstList.get(i).getStationName();
                    if (type.equals("town")) {
                        if (strCountyName.contains("乡")) {
                            strCountyName = strCountyName.substring(0, strCountyName.indexOf('乡') + 1);
                        }
                        if (strCountyName.contains("镇")) {
                            strCountyName = strCountyName.substring(0, strCountyName.indexOf('镇') + 1);
                        }
                    }
                    String weather = "";// 天气信息
                    String windD = "";// 风向信息
                    String windV = "";// 风速信息
                    String windS = "";// 风速信息
                    String windD12 = WebCtrlData.GetAllFx(fcstList.get(i).getWindD().toString().replace("-65535", "0").trim());
                    String windD24 = WebCtrlData.GetAllFx(fcstList.get(i + 1).getWindD().toString().replace("-65535", "0").trim());
                    String windV12 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWindS())));
                    String windV24 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i + 1).getWindS())));
                    String windS12 = String.valueOf(fcstList.get(i).getWindS());
                    String windS24 = String.valueOf(fcstList.get(i + 1).getWindS());
                    if (windD12.equals(windD24)) {
                    windD += windD12;
                    } else {
                        windD += windD12 + "转" + windD24;
                    }
                    if (windV12.equals(windV24)) {
                        windV += windV12;
                    } else {
                        windV += windV12 + "~" + windV24;
                    }
                    if (windS12.equals(windS24)) {
                        windS += windS12 + "m/s";
                    } else {
                        windS += windS12 + "~" + windS24 + "m/s";
                    }
                    if (fcstList.get(i).getWeather1().trim().equals(fcstList.get(i + 1).getWeather1().trim())) {
                        weather += wcd.GetWeatherTq(String.format("%02d",
                                Integer.parseInt(fcstList.get(i).getWeather1().toString().trim())));
                    } else {
                        weather += wcd
                                .GetWeatherTq(String.format("%02d",
                                        Integer.parseInt(fcstList.get(i).getWeather1().toString().trim())))
                                + "转" + wcd.GetWeatherTq(String.format("%02d",
                                Integer.parseInt(fcstList.get(i+1).getWeather1().toString().trim())));
                    }
                    double maxTemp = fcstList.get(i + 1).getMaxTemp();
                    double minTemp = fcstList.get(i + 1).getMinTemp();
                    String pic1 = String.format("%02d",
                            Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather1())));
                    String pic2 = String.format("%02d",
                            Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i + 1).getWeather1())));
                    CityFcstInfo fcstInfo = new CityFcstInfo();
                    fcstInfo.setStationId(strStationID);
                    fcstInfo.setStationName(strCountyName);
                    fcstInfo.setMinTemp(minTemp);
                    fcstInfo.setMaxTemp(maxTemp);
                    fcstInfo.setRain(fcstList.get(i).getRain());
                    fcstInfo.setWindD(windD);
                    fcstInfo.setWindV(windV);
                    fcstInfo.setWindS(windS);
                    fcstInfo.setPic1(pic1);
                    fcstInfo.setPic2(pic2);
                    fcstInfo.setLat(fcstList.get(i).getLatitude());
                    fcstInfo.setLon(fcstList.get(i).getLongitude());
                    DmMapPoint dt = transformService.LonLatConvertToLambert(fcstInfo.getLon(), fcstInfo.getLat());
                    fcstInfo.setX(dt.x);
                    fcstInfo.setY(dt.y);
                    fcstInfo.setWeather1(fcstList.get(i).getWeather1().trim());
                    fcstInfo.setWeather2(fcstList.get(i + 1).getWeather1().trim());
                    fcstInfo.setWeather(weather);
                    fcstInfo.setHumid(String.valueOf(fcstList.get(i).getHumid()) + "%");
                    resultList.add(fcstInfo);
                }
            }
            else {
                List<ForecastInfo> fcstList = qxInfoService.getCityFcst(selectKey);
                int count = fcstList.toArray().length;
                for (int i = 0; i < count; i++) {
                    strStationID = fcstList.get(i).getStationid();
                    strCountyName = fcstList.get(i).getStationname();
                    String weather = "";// 天气信息
                    String windD = "";// 风向信息
                    String windV = "";// 风速信息
                    String windS = "";// 风速信息
                    String windD12 = wcd.GetAllFx(fcstList.get(i).getWindd1().toString().replace("-65535", "0").trim());
                    String windD24 = wcd.GetAllFx(fcstList.get(i).getWindd2().toString().replace("-65535", "0").trim());
                    String windV12 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWind1())));
                    String windV24 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWind2())));
                    String windS12 = String.valueOf(fcstList.get(i).getWind1());
                    String windS24 = String.valueOf(fcstList.get(i).getWind2());
                    if (windD12.equals(windD24)) {
                    windD += windD12;
                    } else {
                        windD += windD12 + "转" + windD24;
                    }
                    if (windV12.equals(windV24)) {
                        windV += windV12;
                    } else {
                        windV += windV12 + "~" + windV24;
                    }
                    if (windS12.equals(windS24)) {
                        windS += windS12 + "m/s";
                    } else {
                        windS += windS12 + "~" + windS24 + "m/s";
                    }
                    if (fcstList.get(i).getWeather1().toString().trim()
                            .equals(fcstList.get(i).getWeather2().toString().trim())) {
                        weather += wcd.GetWeatherTq(String.format("%02d",
                                Integer.parseInt(fcstList.get(i).getWeather1().toString().trim())));
                    } else {
                        weather += wcd
                                .GetWeatherTq(String.format("%02d",
                                        Integer.parseInt(fcstList.get(i).getWeather1().toString().trim())))
                                + "转" + wcd.GetWeatherTq(String.format("%02d",
                                Integer.parseInt(fcstList.get(i).getWeather2().toString().trim())));
                    }
                    double maxTemp = Double.parseDouble(String.format("%.1f", fcstList.get(i).getMaxtemp()));
                    double minTemp = Double.parseDouble(String.format("%.1f", fcstList.get(i).getMintemp()));
                    String pic1 = String.format("%02d", Integer.parseInt(
                            WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather1().toString().trim())));
                    String pic2 = String.format("%02d", Integer.parseInt(
                            WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather2().toString().trim())));
                    CityFcstInfo fcstInfo = new CityFcstInfo();
                    fcstInfo.setStationId(strStationID);
                    fcstInfo.setStationName(strCountyName);
                    fcstInfo.setMinTemp(minTemp);
                    fcstInfo.setMaxTemp(maxTemp);
                    fcstInfo.setRain(fcstList.get(i).getRain());
                    fcstInfo.setWindD(windD);
                    fcstInfo.setWindV(windV);
                    fcstInfo.setWindS(windS);
                    fcstInfo.setPic1(pic1);
                    fcstInfo.setPic2(pic2);
                    fcstInfo.setLat(fcstList.get(i).getLatitude());
                    fcstInfo.setLon(fcstList.get(i).getLongitude());
                    DmMapPoint dt = transformService.LonLatConvertToLambert(fcstInfo.getLon(), fcstInfo.getLat());
                    fcstInfo.setX(dt.x);
                    fcstInfo.setY(dt.y);
                    fcstInfo.setWeather1(fcstList.get(i).getWeather1().toString().trim());
                    fcstInfo.setWeather2(fcstList.get(i).getWeather2().toString().trim());
                    fcstInfo.setWeather(weather);
                    resultList.add(fcstInfo);
                }
            }
        } catch (Exception e) {
            // TODO: 城镇预报查询异常
            e.printStackTrace();
            // log.error(e);
        }
        return resultList;
    }
    /**1
     * 查询最新5条预警信号 1
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/getFiveNewestWarning")
    @ResponseBody
    public Object getFiveNewestWarning(HttpServletRequest request,Model model) throws Exception{
        List<warning> resultList = qxInfoService.getFiveNewestWarning(-1);
        for (warning warn : resultList) {
            ArrayList<CEntity> cEntities = new ArrayList<CEntity>();
            Double lon = 0.0;
            Double lat = 0.0;
            if (!StringUtil.IsNullOrEmpty(warn.getPos())) {
                String[] posArr = warn.getPos().split("\\*");
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        CEntity cEntity = new CEntity();
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                        String strColor = warn.getColor();
                        String colors = "";
                        switch (strColor) {
                            case "蓝色":
                                colors = ColorUtil.Color2String(Color.BLUE);
                                break;
                            case "黄色":
                                colors = ColorUtil.Color2String(Color.YELLOW);
                                break;
                            case "橙色":
                                colors = ColorUtil.Color2String(Color.ORANGE);
                                break;
                            case "红色":
                                colors = ColorUtil.Color2String(Color.RED);
                                break;
                        }
                        // 16进制颜色
                        cEntity.setColor(colors);
                        String[] dotset = pos.split(";");
                        DmMapPoint[] points = new DmMapPoint[dotset.length];
                        Integer index = 0;
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            DmMapPoint dmMapPoint = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                            points[index] = new DmMapPoint(dmMapPoint.x, dmMapPoint.x);
                            index++;
                        }
                        MapCommon dmMapCom = new MapCommon();
                        int[] parts = new int[1];
                        parts[0] = points.length;
                        DmMapPoint dmdotCenter = dmMapCom.getPolygonCenterPoint(points, parts, 1);
                        DmMapPoint ltDotCenter = transformService.LonLatConvertToLambert(dmdotCenter.x, dmdotCenter.y);
                        lon = ltDotCenter.x;
                        lat = ltDotCenter.y;
                        cEntity.setPosArr(tempPos);
                        cEntities.add(cEntity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
            }
            warn.setEntites(cEntities);
            warn.setTime(new DateTime(warn.getAnnouncedtime()).toDateTimeString());
        }
        return resultList;// 查询最新5条预警信号
    }

    /**
     *预警信息页面预警信号功能初始化
     *1
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/showWarning")
    @ResponseBody
    public Object showWarning(HttpServletRequest request, Model model) throws Exception {
    String startDate = request.getParameter("startDate") + " 00:00:00";
    String endDate = request.getParameter("endDate") + " 23:59:59";
    List<warning> resultList = qxInfoService.getWarningInfo(startDate, endDate, -1);// 查询时间段内的预警信息号
        for (warning warn : resultList) {
        ArrayList<CEntity> cEntities = new ArrayList<CEntity>();
        Double lon = 0.0;
        Double lat = 0.0;
        if (!StringUtil.IsNullOrEmpty(warn.getPos())) {
            String[] posArr = warn.getPos().split("\\*");
            for (String pos : posArr) {
                try {
                    if (pos == null || pos.equals("")) {
                        continue;
                    }
                    CEntity cEntity = new CEntity();
                    ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                    String strColor = warn.getColor();
                    String colors = "";
                    switch (strColor) {
                        case "蓝色":
                            colors = ColorUtil.Color2String(Color.BLUE);
                            break;
                        case "黄色":
                            colors = ColorUtil.Color2String(Color.YELLOW);
                            break;
                        case "橙色":
                            colors = ColorUtil.Color2String(Color.ORANGE);
                            break;
                        case "红色":
                            colors = ColorUtil.Color2String(Color.RED);
                            break;
                    }
                    // 16进制颜色
                    cEntity.setColor(colors);
                    String[] dotset = pos.split(";");
                    int i = 0;
                    Integer index = 0;
                    DmMapPoint[] points = new DmMapPoint[dotset.length];
                    DmMapPoint dmDot=null;
                    for (String strDot : dotset) {
                        String[] dot = strDot.split(" ");
                        dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                        DmMapPoint dmMapPoint = transformService.LambertConvertToLonLat(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                        points[index] = new DmMapPoint(dmMapPoint.x, dmMapPoint.x);
                        index++;
                    }
                    MapCommon dmMapCom = new MapCommon();
                    int[] parts = new int[1];
                    parts[0] = points.length;
                    //TODO 4/1气象预警
/*                    DmMapPoint dmdotCenter = dmMapCom.getPolygonCenterPoint(points, parts, 1);
                    DmMapPoint dmMapPoint = transformService.LambertConvertToLonLat(dmdotCenter.x, dmdotCenter.y);*/
                    DmMapPoint dmMapPoint =dmDot;
                    lon = dmMapPoint.x;
                    lat = dmMapPoint.y;
                    tempPos.add(new MyPoint(lon,lat));
                    cEntity.setPosArr(tempPos);
                    cEntities.add(cEntity);
                } catch (Exception e) {
                    System.err.println(e.getStackTrace());
                }
            }
        }
        warn.setEntites(cEntities);
        warn.setTime(new DateTime(warn.getAnnouncedtime()).toDateTimeString());
    }
        return resultList;// 查询时间段内的预警信息号
}

    /**
     *得到预警信息以及坐标位置
     *1
     * @param request
     * @return
     */
    @RequestMapping("/getdzzhxs")
    @ResponseBody
    public Object getdzzhxs(HttpServletRequest request) {
        List<warning> dzList = new ArrayList<warning>();
        try {
            String stryjxx = request.getParameter("stryjxx");
            dzList = qxInfoService.getWarningInfo("", "", Integer.parseInt(stryjxx));// 查询时间段内的预警信息号
            if (dzList != null && dzList.size() > 0) {
                for (warning warn : dzList) {
                    Double lon = 0.0;
                    Double lat = 0.0;
                    if (!StringUtil.IsNullOrEmpty(warn.getPos())) {
                        String[] posArr = warn.getPos().split("\\*");
                        for (String pos : posArr) {
                            try {
                                if (pos == null || pos.equals("")) {
                                    continue;
                                }
                                String[] dotset = pos.split(";");
                                DmMapPoint[] points = new DmMapPoint[dotset.length];
                                DmMapPoint dmDot=null;
                                Integer index = 0;
                                for (String strDot : dotset) {
                                    String[] dot = strDot.split(" ");
                                   dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                                    points[index]  = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                                    index++;
                                }
                                MapCommon dmMapCom = new MapCommon();
                                int[] parts = new int[1];
                                parts[0] = points.length;
/*
                                DmMapPoint dmdotCenter = dmMapCom.getPolygonCenterPoint(points, parts, 1);
*/
//                                DmMapPoint ltDotCenter = transformService.LonLatConvertToLambert(dmdotCenter.x, dmdotCenter.y);
                                DmMapPoint dmdotCenter=dmDot;
                                DmMapPoint ltDotCenter=transformService.LambertConvertToLonLat(dmdotCenter.x, dmdotCenter.y);
                                lon += ltDotCenter.x;
                                lat += ltDotCenter.y;
                            } catch (Exception e) {
                                System.err.println(e.getStackTrace());
                            }
                        }
                        lon = lon / posArr.length;
                        lat = lat / posArr.length;
                    } else {
                        lon = Double.parseDouble(DbConfig.X);
                        lat = Double.parseDouble(DbConfig.Y);
                    }
                    warn.setLon(lon);
                    warn.setLat(lat);
                    warn.setTime(new DateTime(warn.getAnnouncedtime()).toDateTimeString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dzList;
    }

    /**
     * 预警信号查看全部
     *1
     * @param request
     * @return
     */
    @RequestMapping("/getAllwarn")
    @ResponseBody
    public Object getAllwarn(HttpServletRequest request) {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        List<warning> dzList = qxInfoService.getWarningType(startDate, endDate);// 查询时间段内的预警信息号
        String temp = "";
        String tupian = "";
        String county = "";
        if (dzList != null && dzList.size() > 0) {
            for (warning warn : dzList) {
                tupian += warn.getType() + warn.getColor() + ",";
                county += warn.getCounty();
            }
            tupian = tupian.substring(0, tupian.length() - 1);
        }
//        if (county.contains("澧市")) {
        temp = "[{info:\"" + tupian + "\",lon:" + DbConfig.X + ",lat:" + DbConfig.Y + "}]";
//        }
        return temp;
    }

    /**
     * 得到气象预警文档
     *1
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/getQxWarnDoc")
    @ResponseBody
    public Object getQxWarnDoc(HttpServletRequest request, Model model) throws ParseException {
        String docpath = request.getParameter("docpath");
        String docid = qxInfoService.getQxWarnDoc(docpath);
        String servicePath = "";// 服务器文件
        String urlpath ;
        if (operatingSystem.equals("Windows")){
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\QxWarning\\";// 临时文件目录
        }else {
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/QxWarning/";// 临时文件目录
        }

        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存

        String fileName = docpath;// 文件名
        String doctype = "";
        if (docpath!=null) {
            doctype=fileName.split("\\.")[fileName.split("\\.").length - 1];// 文件类型}
        }
            if (doctype.contains("doc")) {
                String pdfPath = urlpath + fileName.replace(doctype, "pdf");
                File pdfFile = new File(pdfPath);
                if (pdfFile.exists()) {
                    servicePath = "Temp\\QxWarning\\" + fileName.replace(doctype, "pdf");
                } else {
                    Map<String, Object> map = new HashMap<String, Object>();
                    map.put("id", docid);
                    map.put("table_name", "base_product");
                    map.put("collectionName", "pdf_file");
                    map.put("advCode", DbConfig.advCode);
                    byte[] data = ms.selectData(map);
                    if (data == null) {
                        return "";
                    }
                    FileUtil.bytesToFile(data, pdfPath);
                    servicePath = "Temp\\QxWarning\\" + fileName.replace(doctype, "pdf");
                }
            }
            servicePath = servicePath.replace("\\", "/");
            return servicePath;
        }

    @RequestMapping("/getQxFwDoc")
    @ResponseBody
    public Object getQxFwDoc() throws ParseException, SQLException, IOException, ClassNotFoundException {
     return    qxInfoService.getQxFwDoc();
    }

    @RequestMapping("/getQxFwPdf")
    @ResponseBody
    public Object getQxFwPdf(HttpServletRequest request, Model model) throws ParseException {
        String docpath = request.getParameter("docpath");// 获取前台文档路径
        if (docpath == null || docpath.equals("")) {
            return "";
        }
        String id = request.getParameter("id");// 获取编号
        if (id == null || id.equals("")) {
            return "";
        }
        String urlpath ;
        if (operatingSystem.equals("Windows")){
            urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\slWarning\\";// 临时文件目录
        }else {
            urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/slWarning/";// 临时文件目录
        }


        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存

        String fileName = docpath.split("\\\\")[docpath.split("\\\\").length - 1];// 文件名
        String doctype = fileName.split("\\.")[fileName.split("\\.").length - 1];// 文件类型
        String servicePath = "";// 服务器文件
        if (doctype.contains("doc")) {
            String pdfPath = urlpath + fileName.replace(doctype, "pdf");
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                if (operatingSystem.equals("Windows")){
                    servicePath = "Temp\\slWarning\\" + fileName.replace(doctype, "pdf");
                }else {
                    servicePath = "Temp/slWarning/" + fileName.replace(doctype, "pdf");
                }

            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", id);
                map.put("table_name", "base_product");
                map.put("collectionName", "pdf_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = ms.selectData(map);
                // 下载doc文件
                if (data == null) {
                    return "";
                }
                FileUtil.bytesToFile(data, pdfPath);
                if (operatingSystem.equals("Windows")){
                    servicePath = "Temp\\slWarning\\" + fileName.replace(doctype, "pdf");
                }else {
                    servicePath = "Temp/slWarning/" + fileName.replace(doctype, "pdf");
                }

            }
        }
        servicePath = servicePath.replace("\\", "/");
        return servicePath;
    }
    /**
     * 初始化QPF
     *1
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/initQpfPage")
    @ResponseBody
    public Object initQpfPage(HttpServletRequest request, Model model) throws ParseException {
        List<Object> arrayList = new ArrayList<>();
        String type = "QPF";
        //查询时间
        collectTime scaleNewDate = qxInfoService.getScaleNewDate(type);
        StringBuilder dateTime = new StringBuilder();
        dateTime.append(scaleNewDate.getYear()+"-");
        dateTime.append(scaleNewDate.getMonth() + "-");
        dateTime.append(scaleNewDate.getDay()+" ");
        //dateTime.append(scaleNewDate.getHour());
        arrayList.add(dateTime.toString());
        arrayList.add(scaleNewDate.getHour());
        return arrayList;
    }

    /***1
     * 展示QPF  地图 类似于雷达的显示 1
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/showQpfMap")
    @ResponseBody
    public Object showQpfMap(HttpServletRequest request, Model model) {
        String datechar = request.getParameter("datechar");
        String datetime = datechar.substring(0, 4) + datechar.substring(5, 7) + datechar.substring(8, 10) + datechar.substring(11, 13);

        String ntimes = request.getParameter("ntimes");
        String drainagearea = request.getParameter("drainagearea");//流域
        if(StringUtil.IsNullOrEmpty(drainagearea))
            drainagearea = DbConfig.DRAINAGEAREA;
        String rstpath = "";
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\QpfMap\\";
        FileUtil.mkDirs(urlpath);// 创建文件夹
        // 当图片达到1000张时清除
        FileUtil.ClearTempFiles(urlpath, 1000);
        String fileName = datetime + "_" + ntimes + ".png";
        String servicePath = urlpath + fileName;
        String path = request.getContextPath();
        String basePath = DbConfig.IP + path + "/Temp/QpfMap/";
        File serviceFile = new File(servicePath);
        if (serviceFile.exists()) {
            rstpath = basePath + fileName;
        } else {
            // 从mongdb获取图片
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("datechar", datetime);
            map.put("type", "QPF");
            map.put("ntimes", ntimes);
            map.put("drainagearea", drainagearea);
            map.put("collectionName", "qpf_png_sl_file");
            map.put("advCode", DbConfig.advCode);
            byte[] data = ms.selectData(map);
            //byte[] data = HttpRequest.get(DbConfig.mongoSelectUrl, map, true).bytes();
            if (data==null){
                rstpath="";
            }else {
                FileUtil.bytesToFile(data, servicePath);
                rstpath = basePath + fileName;
            }
        }
        // 拼接路径
        return rstpath;
    }

    /**1
     * 获取时间点的雷电潜势预报文档
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/showLDDoc")
    @ResponseBody
    public Object showLDDoc(HttpServletRequest request, Model model) throws ParseException {
        String id = request.getParameter("id");// 时间
        String productname = request.getParameter("productname");// 时间
        String servicePath = "";// 服务器文件

        String urlpath ;
        if (operatingSystem.equals("Windows")){
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\LDfile\\";// 临时文件目录
        }else {
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/LDfile/";// 临时文件目录
        }

        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String fileName = productname;// 文件名
        String doctype = "";
        if (fileName != null) {
            doctype = fileName.split("\\.")[fileName.split("\\.").length - 1];// 文件类型
        }
        if (doctype.contains("doc")) {
            String pdfPath = urlpath + fileName.replace(doctype, "pdf");
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                if (operatingSystem.equals("Windows")){
                    servicePath = "Temp\\LDfile\\" + fileName.replace(doctype, "pdf");
                }else {
                    servicePath = "Temp/LDfile/" + fileName.replace(doctype, "pdf");
                }

            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", id);
                map.put("table_name", "base_product");
                map.put("collectionName", "pdf_file");
                byte[] data = ms.selectData(map);
                // 下载doc文件
                if (data == null) {
                    return "";
                }
                FileUtil.bytesToFile(data, pdfPath);
                if (operatingSystem.equals("Windows")){
                    servicePath = "Temp\\LDfile\\" + fileName.replace(doctype, "pdf");
                }else {
                    servicePath = "Temp/LDfile/" + fileName.replace(doctype, "pdf");
                }

            }
        }
        servicePath = servicePath.replace("\\", "/");
        return servicePath;
    }

    /**1
     * 初始化指导预报
     * @return
     */
    @RequestMapping("/initZhiDaoPage")
    @ResponseBody
    public Object initZhiDaoPage() {
        ArrayList<Object> arrayList = new ArrayList<Object>();
        // 获取时间
        shitai_text dKey = qxInfoService.getZhiDaoNewDate();
        // 加载列表
        DateTime newestDateTime = new DateTime(dKey.getDatetime());
        String startDate = newestDateTime.AddDays(-1).toDateString();
        String endDate = newestDateTime.toDateString();
        arrayList.add(startDate);// 时间
        arrayList.add(endDate);// 时间
        return arrayList;
    }

    /**1
     * 查询指导预报
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/getZhiDaoInfo")
    @ResponseBody
    public Object getZhiDaoInfo(HttpServletRequest request, Model model) throws ParseException {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        List<shitai_text> resultList = qxInfoService.getZhiDaoInfo(startDate, endDate);
        return resultList;
    }

    /**1
     * 展示指导预报
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/getZhiDaoTXT")
    @ResponseBody
    public Object getZhiDaoTXT(HttpServletRequest request, Model model) throws ParseException {
        String year = request.getParameter("year");//
        String datetime = request.getParameter("datetime");//
        String filetype = request.getParameter("filetype");//
        String filename = request.getParameter("filename");//
        String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\ZhiDaoTXT\\";// 临时文件目录

        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String fileName = filename + ".txt";// 文件名
        String result = "";// 服务器文件
        String txtPath = urlpath + fileName;
        File txtFile = new File(txtPath);
        if (txtFile.exists()) {
            result = FileUtil.readLogByStringAndEncode(txtPath, "GB2312");
        } else {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("year", year);
            map.put("datetime", datetime);
            map.put("filetype", filetype);
            map.put("filename", filename);
            map.put("collectionName", "shitai_file");
            byte[] data = ms.selectData(map);
            // 下载doc文件
            if (data == null) {
                return "";
            }
            FileUtil.bytesToFile(data, txtPath);
            result = FileUtil.readLogByStringAndEncode(txtPath, "GB2312");
        }
        return result;
    }

    /**1
     * 初始化雷电文档
     * @return
     */
    @RequestMapping("/initWdPage")
    @ResponseBody
    public Object initWdPage() {
        ArrayList<Object> arrayList = new ArrayList<Object>();
        // 获取时间
        base_product dKey = qxInfoService.initWdPage();
        // 加载列表
        DateTime newestDateTime = new DateTime(dKey.getForecasttime());
        String startDate = newestDateTime.AddDays(-7).toDateString();
        String endDate = newestDateTime.toDateString();
        arrayList.add(startDate);// 时间
        arrayList.add(endDate);// 时间
        return arrayList;
    }

    /**1
     * 查询雷电潜势文档
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/getLdWord")
    @ResponseBody
    public Object getLdWord(HttpServletRequest request, Model model) throws ParseException {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        List<base_product> resultList = qxInfoService.getLdWord(startDate, endDate);
        return resultList;
    }

    /**1
     * 文字滚屏效果
     * @return
     * @throws Exception
     */
    @RequestMapping("/initWenZi")
    @ResponseBody
    public Object initWenZi() throws Exception {
        String result = "";
        List<warning> resultList = waternfoService.GetWarnSignalInfoWenZi();// 查询最新的预警信号
        if (resultList != null) {
            for (warning warn : resultList) {
                result += "【" + warn.getArea() + " " + new DateTime(warn.getAnnouncedtime()).toDateTimeString() + "发布" + warn.getType() + warn.getColor() + "预警】：" + warn.getStandard();
            }
        } else {
            result = "";
        }
        return result;
    }
    /**1
     * 三日城镇预报
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/ThreeDayChenZhenYuBao")
    @ResponseBody
    public Object getThreeDayCityFcst(HttpServletRequest request, Model model) {
        TownshipForecastKey selectKey = new TownshipForecastKey();// 查询类
        String time = DateTime.now().toDateString();// 时间
        String sc = "";
        if(DateTime.now().GetHour() >= 8 && DateTime.now().GetHour() < 20)
            sc = "08";
        else if (DateTime.now().GetHour() >= 0 && DateTime.now().GetHour()<8){
            time = DateTime.now().AddDays(-1).toDateTimeString("yyyy-MM-dd") + " 00:00:00"; // 预报时间
            sc = "20";
        } else{
            sc = "20";
        }
        String strStationID = "";
        String strCountyName = "";
        String ntimes = request.getParameter("ntimes");
        int nTimes;
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        WebCtrlData wcd = new WebCtrlData();
        try {
            selectKey.setTimeChar(sc);
            selectKey.setDateChar(DateTime.parseDate(time).toDate());
            if (!StringUtil.IsNullOrEmpty(ntimes)) {
                selectKey.setNTimes(Integer.parseInt(ntimes));
            }
            List<ForecastInfo> fcstList = qxInfoService.getThreeDayCityFcst(selectKey);
            int count = fcstList.toArray().length;
            for (int i = 0; i < count; i++) {
                strStationID = fcstList.get(i).getStationid();
                strCountyName = fcstList.get(i).getStationname();
                String weather = "";// 天气信息
                String windD = "";// 风向信息
                String windV = "";// 风速信息
                String windS = "";// 风速信息
                String windD12 = wcd.GetAllFx(fcstList.get(i).getWindd1().toString().replace("-65535", "0").trim());
                String windD24 = wcd.GetAllFx(fcstList.get(i).getWindd2().toString().replace("-65535", "0").trim());
                String windV12 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWind1())));
                String windV24 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWind2())));
                String windS12 = String.valueOf(fcstList.get(i).getWind1());
                String windS24 = String.valueOf(fcstList.get(i).getWind2());
                if (windD12.equals(windD24)) {
                    windD += windD12;
                } else {
                    windD += windD12 + "转" + windD24;
                }
                if (windV12.equals(windV24)) {
                    windV += windV12;
                } else {
                    windV += windV12 + "~" + windV24;
                }
                if (windS12.equals(windS24)) {
                    windS += windS12 + "m/s";
                } else {
                    windS += windS12 + "~" + windS24 + "m/s";
                }
                if (fcstList.get(i).getWeather1().toString().trim()
                        .equals(fcstList.get(i).getWeather2().toString().trim())) {
                    weather += wcd.GetWeatherTq(String.format("%02d",
                            Integer.parseInt(fcstList.get(i).getWeather1().toString().trim())));
                } else {
                    weather += wcd
                            .GetWeatherTq(String.format("%02d",
                                    Integer.parseInt(fcstList.get(i).getWeather1().toString().trim())))
                            + "转" + wcd.GetWeatherTq(String.format("%02d",
                            Integer.parseInt(fcstList.get(i).getWeather2().toString().trim())));
                }
                double maxTemp = Double.parseDouble(String.format("%.1f", fcstList.get(i).getMaxtemp()));
                double minTemp = Double.parseDouble(String.format("%.1f", fcstList.get(i).getMintemp()));
                String pic1 = String.format("%02d", Integer.parseInt(
                        WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather1().toString().trim())));
                String pic2 = String.format("%02d", Integer.parseInt(
                        WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather2().toString().trim())));
                CityFcstInfo fcstInfo = new CityFcstInfo();
                fcstInfo.setStationId(strStationID);
                fcstInfo.setStationName(strCountyName);
                fcstInfo.setMinTemp(minTemp);
                fcstInfo.setMaxTemp(maxTemp);
                fcstInfo.setRain(fcstList.get(i).getRain());
                fcstInfo.setWindD(windD);
                fcstInfo.setWindV(windV);
                fcstInfo.setWindS(windS);
                fcstInfo.setPic1(pic1);
                fcstInfo.setPic2(pic2);
                fcstInfo.setLat(fcstList.get(i).getLatitude());
                fcstInfo.setLon(fcstList.get(i).getLongitude());
                //
                DmMapPoint dmMapPoint = transformService.LonLatConvertToLambert(fcstInfo.getLon(), fcstInfo.getLat());
                fcstInfo.setX(dmMapPoint.x);
                fcstInfo.setY(dmMapPoint.y);
                fcstInfo.setWeather1(fcstList.get(i).getWeather1().toString().trim());
                fcstInfo.setWeather2(fcstList.get(i).getWeather2().toString().trim());
                fcstInfo.setWeather(weather);
                fcstInfo.setTime(new DateTime(fcstList.get(i).getDatechar()).toDateString());
                resultList.add(fcstInfo);
            }
        } catch (Exception e) {
            // TODO: 城镇预报查询异常
            e.printStackTrace();
            // log.error(e);
        }
        return resultList;
    }
    /**1
     * 道路气象预警查询
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/RoadQxWarning")
    @ResponseBody
    public Object roadQxWarning(HttpServletRequest request, Model model) throws Exception {
        String startDate = DateTime.now().toDateString() + " 00:00:00";
        String endDate = DateTime.now().toDateString() + " 23:59:59";
        List<warning> resultList = qxInfoService.getWarningInfo(startDate, endDate, -1);// 查询时间段内的预警信息号

        //交通道路
        TrafficSearch selectKey = new TrafficSearch();// 查询类
        String types = request.getParameter("type");
        String time = request.getParameter("date") + ":00:00";// 获取开始时间
        selectKey.setTime(time);// 保存在selectKey中
        selectKey.setTypes(types);
        List<Object> resultend = new ArrayList<Object>();
        List<Traffic> traffic = forecastInfoService.getTraffic(selectKey);
        List<TrafficColor> tracolor = new ArrayList<TrafficColor>();
        TrafficColor tracolors = new TrafficColor();
        List<Combatpoint> resultList1 = new ArrayList<Combatpoint>();
        List<ArrayList<MyPoint>> list = new ArrayList<ArrayList<MyPoint>>();
        String strstaNames = "";
        for (Traffic traffici : traffic) {
            Integer level = traffici.getForcastLevel();
            strstaNames = traffici.getStationName();
            if (level == 1) {
                tracolors.setElementValue("一级");
                tracolors.setElementColor(65280);
            }
            if (level == 2) {
                tracolors.setElementValue("二级");
                tracolors.setElementColor(65535);
            }
            if (level == 3) {
                tracolors.setElementValue("三级");
                tracolors.setElementColor(12171775);
            }
            if (level == 4) {
                tracolors.setElementValue("四级");
                tracolors.setElementColor(3947775);
            }
            if (level == 5) {
                tracolors.setElementValue("五级");
                tracolors.setElementColor(191);
            }
            tracolor.add(tracolors);
            selectKey.setStrstaName(strstaNames);

            resultList1 = forecastInfoService.getCoordinate(selectKey);
            String[] coordinate;
            ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
            for (Combatpoint combatpoint : resultList1) {
                coordinate = new String[combatpoint.getRoadcoordinate().split(",").length];
                coordinate = combatpoint.getRoadcoordinate().split( ",");
                for (int i = 0; i < coordinate.length; i += 2) {
                    MyPoint point = new MyPoint(Double.parseDouble(coordinate[i]), Double.parseDouble(coordinate[i + 1]));
                    tempPos.add(point);
                }
                list.add(tempPos);
            }
        }

        for (warning warn : resultList) {
            ArrayList<CEntity> cEntities = new ArrayList<CEntity>();
            DmMapPoint[]  points = null;
            DmMapPoint[]  newpoints = null;
            if (!StringUtil.IsNullOrEmpty(warn.getPos())) {
                String[] posArr = warn.getPos().split("\\*");
                for (String pos : posArr) {
                    try {
                        if (pos == null || pos.equals("")) {
                            continue;
                        }
                        CEntity cEntity = new CEntity();
                        ArrayList<MyPoint> tempPos = new ArrayList<MyPoint>();
                        String strColor = warn.getColor();
                        String colors = "";
                        switch (strColor) {
                            case "蓝色":
                                colors = ColorUtil.Color2String(Color.BLUE);
                                break;
                            case "黄色":
                                colors = ColorUtil.Color2String(Color.YELLOW);
                                break;
                            case "橙色":
                                colors = ColorUtil.Color2String(Color.ORANGE);
                                break;
                            case "红色":
                                colors = ColorUtil.Color2String(Color.RED);
                                break;
                        }
                        // 16进制颜色
                        cEntity.setColor(colors);
                        String[] dotset = pos.split(";");
                        Integer index = 0;
                        points = new DmMapPoint[dotset.length];
                        for (String strDot : dotset) {
                            String[] dot = strDot.split(" ");
                            DmMapPoint dmDot = new DmMapPoint(Double.parseDouble(dot[0]), Double.parseDouble(dot[1]));
                            DmMapPoint dmMapPoint = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                            MyPoint dm = new MyPoint(dmMapPoint.x, dmMapPoint.y);
                            tempPos.add(dm);
                            points[index] = dmDot;
                            index++;
                        }
                        MapCommon dmMapCom = new MapCommon();
                        newpoints= dmMapCom.insertDensity(points, 30, 1.5);
                        tempPos = new ArrayList<MyPoint>();
                        for (int s = 0; s < newpoints.length; s++) {
                            DmMapPoint dmDot = newpoints[s];
                            DmMapPoint ltDot = transformService.LambertConvertToLonLat(dmDot.x, dmDot.y);
                            MyPoint dm = new MyPoint(ltDot.x, ltDot.y);
                            tempPos.add(dm);
                            newpoints[s]=dmDot;
                        }
                        cEntity.setPosArr(tempPos);
                        cEntities.add(cEntity);
                    } catch (Exception e) {
                        System.err.println(e.getStackTrace());
                    }
                }
            }
            warn.setEntites(cEntities);
            warn.setTime(new DateTime(warn.getAnnouncedtime()).toDateTimeString());
        }
        return resultList;// 查询时间段内的预警信息号
    }
    /**1
     * 得到雷电预警描述
     * @param request
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping("/getLDWarning")
    @ResponseBody
    public Object getHXWarning(HttpServletRequest request, Model model) throws Exception {
        thunder_fcst newestDate = qxInfoService.getLDNewDate();
        // 加载列表
        String sc = newestDate.getForecasttime();
        String time = new DateTime(newestDate.getReporttime()).toDateString();
        String sx = request.getParameter("sx");// 时效
        List<thunder_fcst> resultList = qxInfoService.getThunderFcst(time, sc, sx);// 查询潜势预报
        Double max = 0.0;
        String level = "";
        String newtime = "";
        for (thunder_fcst thunder : resultList) {
            String ldLevel = thunder.getPredictlevel().toString().trim();
            Double predictprobability = thunder.getPredictprobability();
            predictprobability = (double) Math.round(predictprobability * 100) / 100;
            if (predictprobability > max) {
                max = predictprobability;
                level = ldLevel;
                newtime = new DateTime(thunder.getReporttime()).toDateTimeString();
            }
        }
        String imageName = "";
        switch (level) {
            case "强":
                imageName = "红色，发生雷电活动的可能性非常大";
                break;
            case "中":
                imageName = "橙色，发生雷电活动的可能性很大";
                break;
            case "弱":
                imageName = "黄色，发生雷电活动的可能性较大";
                break;
            case "无":
                imageName = "蓝色，无发生雷电活动的可能性";
                break;
        }
        String result = "";
        if (resultList != null && resultList.size() > 0) {
            if (!StringUtil.IsNullOrEmpty(resultList.get(0).getPredictlevel()))
                result = newtime + "：" + "根据雷电潜势预报资料分析，全市雷电潜势预报概率最高为" + imageName;
            else
                result = newtime + "：暂无相关预警区描述!";
        }
        return result;
    }
    /***1
     * 得到最近站点未来三天天气预报
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/getNearStaThreeForecast")
    @ResponseBody
    public Object getNearStaThreeForecast(HttpServletRequest request, Model model) throws Exception {
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        String lon = request.getParameter("lon");
        String lat = request.getParameter("lat");
        String time = DateTime.now().toDateString();// 时间
        String sc = (DateTime.now().GetHour() >= 8 && DateTime.now().GetHour() <= 20) ? "08" : "20";// 时次
        if(DateTime.now().GetHour() >= 8 && DateTime.now().GetHour() < 20)
            sc = "08";
        else if (DateTime.now().GetHour() >= 0 && DateTime.now().GetHour()<8){
            time = DateTime.now().AddDays(-1).toDateTimeString("yyyy-MM-dd") + " 00:00:00"; // 预报时间
            sc = "20";
        } else{
            sc = "20";
        }
        String strStationID = "";
        String strCountyName = "";
        int nTimes = 72;
        TownshipForecastKey selectKey = new TownshipForecastKey();// 查询类
        selectKey.setTimeChar(sc);
        selectKey.setDateChar(DateTime.parseDate(time).toDate());
        selectKey.setNTimes(nTimes);
        List<TownshipForecast> fcstList = qxInfoService.getNearStaThreeForecast(selectKey, lon, lat);
        WebCtrlData wcd = new WebCtrlData();
        int count = fcstList.toArray().length;
        for (int i = 0; i < count; i += 2) {
            strStationID = fcstList.get(i).getStationID();
            strCountyName = fcstList.get(i).getStationName();
            if (strCountyName.contains("乡")) {
                strCountyName = strCountyName.substring(0, strCountyName.indexOf('乡') + 1);
            }
            if (strCountyName.contains("镇")) {
                strCountyName = strCountyName.substring(0, strCountyName.indexOf('镇') + 1);
            }
            String weather = "";// 天气信息
            String windD = "";// 风向信息
            String windV = "";// 风速信息
            String windS = "";// 风速信息
            String windD12 = wcd.GetAllFx(fcstList.get(i).getWindD().toString().replace("-65535", "0").trim());
            String windD24 = wcd.GetAllFx(fcstList.get(i + 1).getWindD().toString().replace("-65535", "0").trim());
            String windV12 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWindS())));
            String windV24 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i + 1).getWindS())));
            String windS12 = String.valueOf(fcstList.get(i).getWindS());
            String windS24 = String.valueOf(fcstList.get(i + 1).getWindS());
            if (windD12.equals(windD24)) {
                windD += windD12;
            } else {
                windD += windD12 + "转" + windD24;
            }
            if (windV12.equals(windV24)) {
                windV += windV12;
            } else {
                windV += windV12 + "~" + windV24;
            }
            if (windS12.equals(windS24)) {
                windS += windS12 + "m/s";
            } else {
                windS += windS12 + "~" + windS24 + "m/s";
            }
            if (fcstList.get(i).getWeather1().trim().equals(fcstList.get(i + 1).getWeather1().trim())) {
                weather += fcstList.get(i).getWeather1().trim();
            } else {
                weather += fcstList.get(i).getWeather1().trim() + "转"
                        + fcstList.get(i + 1).getWeather1().trim();
            }
            double maxTemp = fcstList.get(i).getMaxTemp() > fcstList.get(i + 1).getMaxTemp()
                    ? fcstList.get(i).getMaxTemp() : fcstList.get(i + 1).getMaxTemp();
            double minTemp = fcstList.get(i).getMinTemp() > fcstList.get(i + 1).getMinTemp()
                    ? fcstList.get(i + 1).getMinTemp() : fcstList.get(i).getMinTemp();
            String pic1 = String.format("%02d",
                    Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather1())));
            String pic2 = String.format("%02d",
                    Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i + 1).getWeather1())));
            CityFcstInfo fcstInfo = new CityFcstInfo();
            fcstInfo.setStationId(strStationID);
            fcstInfo.setStationName(strCountyName);
            fcstInfo.setMinTemp(minTemp);
            fcstInfo.setMaxTemp(maxTemp);
            fcstInfo.setRain(fcstList.get(i).getRain());
            fcstInfo.setWindD(windD);
            fcstInfo.setWindV(windV);
            fcstInfo.setWindS(windS);
            fcstInfo.setPic1(pic1);
            fcstInfo.setPic2(pic2);
            fcstInfo.setLat(fcstList.get(i).getLatitude());
            fcstInfo.setLon(fcstList.get(i).getLongitude());
            DmMapPoint dt = transformService.LonLatConvertToLambert(fcstInfo.getLon(), fcstInfo.getLat());
            fcstInfo.setX(dt.x);
            fcstInfo.setY(dt.y);
            fcstInfo.setWeather1(fcstList.get(i).getWeather1().trim());
            fcstInfo.setWeather2(fcstList.get(i + 1).getWeather1().trim());
            fcstInfo.setWeather(weather);
            fcstInfo.setHumid(String.valueOf(fcstList.get(i).getHumid()) + "%");
            resultList.add(fcstInfo);
        }
        return resultList;
    }

    /***1
     * 预报  七张图
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetForecastPicInfo")
    @ResponseBody
    public Object getForecastPicInfo(HttpServletRequest request, Model model) throws ParseException {
        List<ForecastRain> rains = new ArrayList<>();

        String datechar = request.getParameter("datechar");
        String timechar = request.getParameter("sc");
        String forecast = request.getParameter("sx");
        String drainagearea = request.getParameter("drainagearea");//流域
        if(StringUtil.IsNullOrEmpty(drainagearea))
            drainagearea = DbConfig.DRAINAGEAREA;
        String picpath = "";
        DateTime time = DateTime.now();
        String[] types = new String[]{forecast};
        String newestDate = datechar + ":00";//.GetForecastTimeInfo();
        String strtime = newestDate.substring(0, 4) + "-" + newestDate.substring(5, 7) + "-" + newestDate.substring(8, 10)  + ' ' + timechar + ":00:00";
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d1 = sdf1.parse(strtime);
        String hours = getDatePoor(time.toDate(), d1);


        String path = request.getContextPath();
        String basePath = DbConfig.IP + path
                + "/Temp/ForecastRain/";
        String urlpath;
        if (operatingSystem.equals("Windows")){
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\ForecastRain\\";// 临时文件目录
        }else {
             urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/ForecastRain/";// 临时文件目录
        }

        FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
        String datetime = newestDate.substring(0, 4) + "-" + newestDate.substring(5, 7) + "-" + newestDate.substring(8, 10);
        for (String type : types) {
            ForecastRain r = new ForecastRain();
            String fileName = datetime + "_" + timechar + "_" + type + ".png";
            String servicePath = urlpath + fileName;// 服务器文件
            File serviceFile = new File(servicePath);// 服务器文件
            if (serviceFile.exists()) {// 把文件上传到服务器
                picpath = basePath + fileName;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("datetime", datetime);
                map.put("timechar", timechar);
                map.put("sx", forecast);
                map.put("drainagearea", drainagearea);
                map.put("collectionName", "yb_png_sl_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = ms.selectData(map);
                if (data==null || data.equals("")) {
                    picpath = "";
                } else {
                    FileUtil.bytesToFile(data, servicePath);
                    picpath = basePath + fileName;
                }
            }
            r.setPath(picpath);
            String starttime = new DateTime(d1).AddHours((Integer.parseInt(hours) / 3) * 3).toDateTimeString("MM-dd HH") + "时";
            String endtime = new DateTime(d1).AddHours((Integer.parseInt(hours) / 3) * 3).AddHours(Integer.parseInt(type)).toDateTimeString("MM-dd HH") + "时";
            r.setTime(starttime + " - " + endtime);
            rains.add(r);
        }
        return new ResultObj("查询成功", rains, true);
    }
    /***
     * 预报雨量结果
     */
    public class ForecastRain {
        private String path;
        private String time;

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }

        public String getTime() {
            return time;
        }

        public void setTime(String time) {
            this.time = time;
        }

    }
    /**
     * 初始化常规服务界面
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/initWordPage")
    @ResponseBody
    public Object initWordPage(HttpServletRequest request, Model model) {
        String types = request.getParameter("type");
        List<job_model> arrayList = forecastInfoService.initWordPage(types);
        return arrayList;
    }

    /**
     * 得到常规服务文档
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/getCommonWord")
    @ResponseBody
    public Object getCommonWord(HttpServletRequest request, Model model) throws ParseException {
        String bigtype = request.getParameter("bigtype");
        String smalltype = request.getParameter("smalltype");
        List<summary_product> resultList = forecastInfoService.getCommonWord(bigtype, smalltype,request);
        return resultList;
    }
    @RequestMapping("/getCommonWordType")
    @ResponseBody
    public Object getCommonWordType(HttpServletRequest request, Model model) throws ParseException {
        List<job_model> resultList = forecastInfoService.getCommonWordType();
        return resultList;
    }


    /**。1
     * 得到常规服务文档
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/getSYCommonWord")
    @ResponseBody
    public Object getSYCommonWord(HttpServletRequest request, Model model) throws ParseException {
        String bigtype = request.getParameter("bigtype");
        String smalltype = request.getParameter("smalltype");
        List<summary_product> resultList = forecastInfoService.getSYCommonWord(bigtype, smalltype);
        return resultList;
    }

    /**1
     * 显示常规服务文档
     * @param request
     * @param model
     * @return 1
     * @throws ParseException
     */
    @RequestMapping("/showCommonDoc")
    @ResponseBody
    public Object showCommonDoc(HttpServletRequest request, Model model) throws ParseException {
        String servicePath = "";
        String id = request.getParameter("id"); // 获取编号
        String fileName = request.getParameter("filename");
        String urlpath ;
        if (operatingSystem.equals("Windows")){
            urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\CommonWord\\"; // 临时文件目录
        }else {
            urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/CommonWord/"; // 临时文件目录
        }

        FileUtil.mkDirs(urlpath); // 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000); // 清除缓存
        String doctype = fileName.split("\\.")[fileName.split("\\.").length - 1]; // 文件类型
        if (doctype.contains("doc")) {
            String localPath = urlpath + fileName;
            String pdfPath = urlpath + fileName.replace(doctype, "pdf");
            File pdfFile = new File(pdfPath);
            if (pdfFile.exists()) {
                servicePath = "Temp\\CommonWord\\" + fileName.replace(doctype, "pdf");
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", id);
                map.put("table_name", "summary_product");
                map.put("collectionName", "pdf_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = ms.selectData(map);
                // 下载doc文件
                if (data == null) {
                    return "";
                }
                if (data.length > 0) {
                    FileUtil.bytesToFile(data, pdfPath);
                    File localFile = new File(pdfPath); // 本地文件
                    if (localFile.exists()) {
                        try {
                            servicePath = "Temp\\CommonWord\\" + fileName.replace(doctype, "pdf");
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        servicePath = servicePath.replace("\\", "/");
        return servicePath;
    }


    /**1
     * 下载常规服务文档
     * @param request
     * @param response
     * @param model
     * @throws Exception
     */
    @RequestMapping("/DownCommonDoc")
    @ResponseBody
    public void downCommonDoc(HttpServletRequest request, HttpServletResponse response, Model model)
            throws Exception {
        String servicePath = "";
        String localPath = "";
        String id = request.getParameter("did"); // 获取编号
        String fileName = request.getParameter("dname");
        String urlpath =
                request.getSession().getServletContext().getRealPath("/") + "Temp\\CommonWord\\"; // 临时文件目录
        FileUtil.mkDirs(urlpath); // 创建文件夹，生成多级目录
        FileUtil.ClearTempFiles(urlpath, 1000); // 清除缓存
        String doctype = fileName.split("\\.")[fileName.split("\\.").length - 1]; // 文件类型
        if (doctype.contains("doc")) {
            localPath = urlpath + fileName;
            File pdfFile = new File(localPath);
            if (pdfFile.exists()) {
                servicePath = "Temp\\CommonWord\\" + fileName;
            } else {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", id);
                map.put("table_name", "summary_product");
                map.put("collectionName", "doc_file");
                map.put("advCode", DbConfig.advCode);
                byte[] data = ms.selectData(map);
                if (data.length > 0) {
                    FileUtil.bytesToFile(data, localPath);
                    // 下载doc文件
                    File localFile = new File(localPath); // 本地文件
                    if (localFile.exists()) {
                        try {
                            servicePath = "Temp\\CommonWord\\" + fileName;
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        String realPath = request.getSession().getServletContext().getRealPath("/Temp/CommonWord/");
        File file = new File(realPath, fileName);
        if (file.exists()) {
            String fileName1 = URLEncoder.encode(file.getName(), "UTF-8");
            response.setContentType("application/x-download");
            response.setContentLengthLong(file.length());
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName1);
            try (InputStream in = new FileInputStream(file);
                 OutputStream out = response.getOutputStream()) {
                IOUtils.copy(in, out);
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else {

        }
    }
    /**1
     * 下载常规服务文档
     * @param request
     * @param response
     * @param model
     * @throws Exception
     */
    @RequestMapping("/Getword")
    @ResponseBody
    public void getWord(HttpServletRequest request, HttpServletResponse response, Model model)
            throws Exception {
        String serviceFilePath = "";
        serviceFilePath = request.getSession().getServletContext().getRealPath("/Temp/CommonWord/");
        String fileName = request.getParameter("filename");

        File file = null;
        InputStream fin = null;
        ServletOutputStream out = null;
        try {

            file = new File(serviceFilePath, fileName);
            fin = new FileInputStream(file);

            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            // 设置浏览器以下载的方式处理该文件名
            String fileName1 = "环保产品生成.doc";
            response.setHeader(
                    "Content-Disposition",
                    "attachment;filename=".concat(String.valueOf(URLEncoder.encode(fileName1, "UTF-8"))));
            out = response.getOutputStream();
            byte[] buffer = new byte[512]; // 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } finally {
            if (fin != null) fin.close();
            if (out != null) out.close();
            if (file != null) file.delete(); // 删除临时文件
        }
    }
    /*************华丽分割线***********
     * 1、格点数据获取
     ********************************/

    /**
     * 初始化格点显示页面
     *1
     * @param request
     * @return
     */
    @RequestMapping("/InitFcstGridPage")
    @ResponseBody
    public Object initFcstGridPage(HttpServletRequest request) {
        ArrayList arr = new ArrayList();
        List<Map> time = gridDataService.getGridNewestDate(new String[]{"欧洲最新时间", "省台最新时间"});
        List<GridAddName> addname = gridDataService.getGridAddName();
        time.get(0).put("mappedpath","24041220");
        time.get(1).put("mappedpath","24041220");
        arr.add(time);
        arr.add(addname);
        return arr;
    }

    /**
     * 获取最新格点时间
     *1
     * @param request
     * @return
     */
    @RequestMapping("/GetGridNewestDate")
    @ResponseBody
    public Object GetGridNewestDate(HttpServletRequest request) {
        return gridDataService.getGridNewestDate(new String[]{"欧洲最新时间", "省台最新时间"});
    }

    /**
     * 获取格点数据
     *1
     * @param request
     * @param gridPrams 格点条件参数
     * @param model
     * @return
     */
    @RequestMapping("/GetGridData")
    @ResponseBody
    public Object getGridData(HttpServletRequest request, GridFile gridPrams, Model model) {
        //获取mongodb文件
        Object result = null;
        try {
            String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\grid\\";
//            if (gridPrams.getType().toLowerCase().contains("uvuv")) {//EDA10
            if (gridPrams.getType().toUpperCase().contains("EDA10")) {//EDA10
                String[] winds = gridDataService.getWindGridData(urlpath, gridPrams);
                if (winds[0].length() > 0 && winds[1].length() > 0) {
                    result = GridUtil.ReadWinGridFiles(winds[0], winds[1]);
                }
            } else {
                String gridfile = gridDataService.getGridData(urlpath, gridPrams);
                if (gridfile.length() > 0) {
                    result = GridUtil.ReadGridFile(gridfile);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @RequestMapping("/GetGridData1")
    @ResponseBody
    public Object getGridData1(HttpServletRequest request, GridFile gridPrams, Model model, HttpServletResponse response) {
        // 获取mongodb文件
        Object result = null;
        String type = gridPrams.getType();
        String paramtype = "雨量";

        if (type.equals("ER03")) {
            paramtype = "雨量";
        } else if (type.equals("ERH")) {
            paramtype = "湿度";
        } else if (type.equals("ECT")) {
            paramtype = "云量";
        } else if (type.equals("EDA10.U")) {
            paramtype = "风速";
        } else if (type.equals("TMP")) {
            paramtype = "温度";
        }
        ArrayList<My3DPoint> gridData=null;


        try {
            // 获取文件路径并获取grid数据
            String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\grid\\";
            String gridfile = gridDataService.getGridData(urlpath, gridPrams);
            List<ElemContourSet> contourSet = skInfoService.getElemContourSet(paramtype);

            Color[] colors = new Color[contourSet.size()];  // 事先确定颜色数组的大小
            double[] valueRanges = new double[contourSet.size()];  // 事先确定值范围数组的大小
            int index = 0;
            for (ElemContourSet set : contourSet) {
                valueRanges[index] = set.getElementValue();  // 存储元素值
                int color = set.getElementColor();
                int b = color & 0xff;
                int g = (color >> 8) & 0xff;
                int r = (color >> 16) & 0xff;
                String color16 = String.format("#%02X%02X%02X", r, g, b);
                colors[index] = Color.decode(color16);  // 存储颜色
                index++;
            }

            // 假设 gridData 是你获取的文件数据，转换为二维数组（或其他合适的数据结构）
             gridData = parseGridData(gridfile);  // 根据实际文件解析数据

            // 根据颜色等级处理并生成图像
            BufferedImage gridImage = generateGridImage(gridfile, gridData, colors, valueRanges);


            // 获取Tomcat服务器的路径，并存储生成的图片
            String imagePath = request.getSession().getServletContext().getRealPath("/") + "Temp\\gridpng\\";
            File imageDir = new File(imagePath);
            if (!imageDir.exists()) {
                imageDir.mkdirs();  // 创建目录
            }

            // 生成唯一的文件名
            String imageFileName = "grid_image_" + System.currentTimeMillis() + ".png";
            File imageFile = new File(imageDir, imageFileName);

            // 将图片保存到指定路径
            ImageIO.write(gridImage, "PNG", imageFile);

            // 返回图片的 URL（或者返回文件名，前端可以根据此 URL 获取图片）
            String imageUrl = "/Temp/gridpng/" + imageFileName;

            // 返回给前端：可以用 Map 或者封装成一个对象
            result = new HashMap<>();
            ((Map<String, Object>) result).put("imageUrl", imageUrl);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }
    private  ArrayList<My3DPoint> parseGridData(String gridfile) {
        ArrayList<My3DPoint> pList = new ArrayList<>();
        try {
            File gridFile = new File(gridfile);
            if (gridFile.exists()) {
                GridAnalysis GridAnalysis = new GridAnalysis();
                GridAnalysis.openFile(gridfile);  // 打开网格文件
                DmGridInfo gridInfo = GridAnalysis.getGridInfo();
                double xmin = gridInfo.getxMin();
                double ymin = gridInfo.getyMin();
                double xmax = gridInfo.getxMax();
                double ymax = gridInfo.getyMax();
                int row = gridInfo.getRows();
                int col = gridInfo.getCols();

                // 计算每个网格单元的行跨度和列跨度
                double rowSpan = (ymax - ymin) / (row+1);
                double colSpan = (xmax - xmin) / (col+1);

                // // 初始化二维数组来存储每个网格点的数据
                // gridData = new double[col * 2];  // 每列存储 x 和 y 坐标

                // 遍历每个网格点，计算其坐标或值
                for (int i = 0; i < row; i++) {
                    for (int j = 0; j < col; j++) {
                        double x = xmin + j * colSpan;
                        double y = ymin + i * rowSpan;
                        double z = Double.parseDouble(String.format("%.1f",GridAnalysis.getValue(i, j)));
                        My3DPoint point = new My3DPoint(x, y, z);
                        pList.add(point);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();  // 异常处理
        }

        return pList;  // 返回网格数据
    }

    // 根据grid数据生成图像的方法
    private BufferedImage generateGridImage(String gridfile,ArrayList<My3DPoint> gridData, Color[] colors, double[] valueRanges) {
        GridAnalysis GridAnalysis = new GridAnalysis();
        GridAnalysis.openFile(gridfile);  // 打开网格文件
        DmGridInfo gridInfo1 = GridAnalysis.getGridInfo();
        int width = gridInfo1.getCols();
        int height = gridInfo1.getRows();

        // 创建一个BufferedImage来绘制grid数据
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = image.createGraphics();
        // 设置背景透明
        g2d.setComposite(AlphaComposite.Clear);
        g2d.fillRect(0, 0, image.getWidth(), image.getHeight());
        // 填充颜色
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                int n = (y+1)*(x+1) - 1;
                double value = gridData.get(n).getZ(); // 获取grid的值
                Color color = mapValueToColor(value, colors, valueRanges); // 将值映射为颜色
                if (value == 0||color.getRed()==253) {
                    // 设置完全透明 (ARGB中的A=0)
                    image.setRGB(x, y, 0x00000000);
                } else {
                    image.setRGB(x, y, color.getRGB()); // 设置对应像素的颜色
                }
            }
        }
        g2d.dispose();  // 释放资源
        return image;
    }

    // 颜色映射函数，根据值返回对应颜色
    private Color mapValueToColor(double value, Color[] colors, double[] valueRanges) {
        // 找到值所属的区间，并返回对应的颜色
        for (int i = 0; i < valueRanges.length - 1; i++) {
            if (value >= valueRanges[i] && value < valueRanges[i + 1]) {
                return colors[i];  // 返回对应区间的颜色
            }
        }
        return colors[colors.length - 1];  // 如果值超出最大范围，返回最后一个颜色
    }
    /**
     * 获取某一点格点插值值
     *1
     * @param request
     * @param gridPrams 格点条件参数
     * @param model
     * @return
     */
    @RequestMapping("/GetPointGridData")
    @ResponseBody
    public Object getPointGridData(HttpServletRequest request, GridFile gridPrams, Model model) {
        //获取mongodb文件
        Object result = null;
        try {
            Double lon = Double.parseDouble(request.getParameter("lon"));
            Double lat = Double.parseDouble(request.getParameter("lat"));
            String urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\grid\\";
//            if (gridPrams.getType().toLowerCase().contains("uv")) {
            if (gridPrams.getType().toUpperCase().contains("EDA10")) {//EDA10
                String[] winds = gridDataService.getWindGridData(urlpath, gridPrams);
                if (winds[0].length() > 0 && winds[1].length() > 0) {
                    GridAnalysis ugrid = new GridAnalysis();
                    GridAnalysis vgrid = new GridAnalysis();
                    ugrid.openFile(winds[0]);
                    ugrid.openFile(winds[1]);

                    double[] winduv = GridUtil.UVConvertToWind(ugrid.getElevationAt(lon, lat), vgrid.getElevationAt(lon, lat));
                    WindPoint windPoint = new WindPoint(lon, lat, winduv[1],winduv[0]);
                    result = windPoint;
                }
            } else {
                String gridfile = gridDataService.getGridData(urlpath, gridPrams);
                if (gridfile.length() > 0) {
                    GridAnalysis GridAnalysis = new GridAnalysis();
                    GridAnalysis.openFile(gridfile);
                    My3DPoint gridvalue = new My3DPoint(lon, lat,
                            Double.parseDouble(String.format("%.1f", GridAnalysis.getElevationAt(lon, lat))));
                    result = gridvalue;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /****1
     * 获取七天城镇预报  两个地方用到
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetSevenForecast")
    @ResponseBody
    public Object getSevenForecast(HttpServletRequest request, Model model) {
        Object list = skInfoService.getSevenForecast(request);
        return list;
    }

    /****1
     * 获取七天城镇预报  两个地方用到
     * @param request
     * @param
     * @return
     */
    @RequestMapping("/getSevenTownForecast")
    @ResponseBody
    Object getSevenTownForecast(HttpServletRequest request){
        Object list = skInfoService.getSevenTownForecast(request);
        return list;
    }

    /***
     * 乡镇预报 1
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/XiangZhenYuBao")
    @ResponseBody
    public Object xiangZhenYuBao(HttpServletRequest request, Model model) {
        TownshipForecastKey selectKey = new TownshipForecastKey();// 查询类
        DateTime currentTime = DateTime.now();
        String time = currentTime.toDateTimeString("yyyy-MM-dd") + " 00:00:00"; // 预报时间
        String sc = (currentTime.GetHour() >= 8 && currentTime.GetHour() < 20 ? "08" : "20"); // 预报时次
        if(currentTime.GetHour() >= 8 && currentTime.GetHour() < 20)
            sc = "08";
        else if (currentTime.GetHour() >= 0 && currentTime.GetHour()<8){
            time = currentTime.AddDays(-1).toDateTimeString("yyyy-MM-dd") + " 00:00:00"; // 预报时间
            sc = "20";
        } else{
            sc = "20";
        }
        String sx = "24"; // 时效
        String cityId = request.getParameter("cityId");// 城市
        String county = request.getParameter("county");// 区市
        if (StringUtil.IsNullOrEmpty(county))
            county = "澧市";
        String strStationID = "";
        String strCountyName = "";
        int nTimes;
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        WebCtrlData wcd = new WebCtrlData();
        try {
            nTimes = Integer.parseInt(sx);
            if (!(cityId == null) && !cityId.equals("")) {
                selectKey.setStationID(cityId);// 站点号
            }
            selectKey.setNTimes(nTimes);
            selectKey.setTimeChar(sc);
            selectKey.setDateChar(DateTime.parseDate(time).toDate());
            List<TownshipForecast> fcstList = skInfoService.getTownshipFcst(selectKey, county);
            int count = fcstList.toArray().length;
            for (int i = 0; i < count; i += 2) {
                strStationID = fcstList.get(i).getStationID();
                strCountyName = fcstList.get(i).getStationName();
                if (strCountyName.contains("乡")) {
                    strCountyName = strCountyName.substring(0, strCountyName.indexOf('乡') + 1);
                }
                if (strCountyName.contains("镇")) {
                    strCountyName = strCountyName.substring(0, strCountyName.indexOf('镇') + 1);
                }
                String weather = "";// 天气信息
                String windD = "";// 风向信息
                String windV = "";// 风速信息
                String windS = "";// 风速信息
                String windD12 = wcd.GetAllFx(fcstList.get(i).getWindD().toString().replace("-65535", "0").trim());
                String windD24 = wcd.GetAllFx(fcstList.get(i + 1).getWindD().toString().replace("-65535", "0").trim());
                String windV12 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWindS())));
                String windV24 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i + 1).getWindS())));
                String windS12 = String.valueOf(fcstList.get(i).getWindS());
                String windS24 = String.valueOf(fcstList.get(i + 1).getWindS());
                if (windD12.equals(windD24)) {
                    windD += windD12;
                } else {
                    windD += windD12 + "转" + windD24;
                }
                if (windV12.equals(windV24)) {
                    windV += windV12;
                } else {
                    windV += windV12 + "~" + windV24;
                }
                if (windS12.equals(windS24)) {
                    windS += windS12 + "m/s";
                } else {
                    windS += windS12 + "~" + windS24 + "m/s";
                }
                if (fcstList.get(i).getWeather1().trim().equals(fcstList.get(i + 1).getWeather1().trim())) {
                    weather += fcstList.get(i).getWeather1().trim();
                } else {
                    weather += fcstList.get(i).getWeather1().trim() + "转"
                            + fcstList.get(i + 1).getWeather1().trim();
                }
                double maxTemp = fcstList.get(i).getMaxTemp() > fcstList.get(i + 1).getMaxTemp()
                        ? fcstList.get(i).getMaxTemp() : fcstList.get(i + 1).getMaxTemp();
                double minTemp = fcstList.get(i).getMinTemp() > fcstList.get(i + 1).getMinTemp()
                        ? fcstList.get(i + 1).getMinTemp() : fcstList.get(i).getMinTemp();
                String pic1 = String.format("%02d",
                        Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather1())));
                String pic2 = String.format("%02d",
                        Integer.parseInt(WebCtrlData.WeatherNameToPicPath(fcstList.get(i + 1).getWeather1())));
                CityFcstInfo fcstInfo = new CityFcstInfo();
                fcstInfo.setDatechar(DateTime.parseDate(time).toDate());
                fcstInfo.setTimechar(sc);
                fcstInfo.setStationId(strStationID);
                fcstInfo.setStationName(strCountyName);
                fcstInfo.setMinTemp(minTemp);
                fcstInfo.setMaxTemp(maxTemp);
                fcstInfo.setRain(fcstList.get(i).getRain());
                fcstInfo.setWindD(windD);
                fcstInfo.setWindV(windV);
                fcstInfo.setWindS(windS);
                fcstInfo.setPic1(pic1);
                fcstInfo.setPic2(pic2);
                fcstInfo.setLat(fcstList.get(i).getLatitude());
                fcstInfo.setLon(fcstList.get(i).getLongitude());
                fcstInfo.setWeather1(fcstList.get(i).getWeather1().trim());
                fcstInfo.setWeather2(fcstList.get(i + 1).getWeather1().trim());
                fcstInfo.setWeather(weather);
                fcstInfo.setHumid(String.valueOf(fcstList.get(i).getHumid()) + "%");
                resultList.add(fcstInfo);
            }
        } catch (Exception e) {
            // TODO: 城镇预报查询异常
            e.printStackTrace();
            return new ResultObj("查询失败", e.getMessage(), false);
        }
        return new ResultObj("查询成功", resultList, true);
    }
    /***1
     * 获取预警信号  当天
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetWarnSignalInfo")
    @ResponseBody
    public Object getWarnSignalInfo(HttpServletRequest request, Model model) {
        List<Object> rltList = new ArrayList<>();
        Object list = skInfoService.getWarnSignalInfo();
        rltList.add(list);
        String stationname = request.getParameter("stationname");//站点名称
        if (!StringUtil.IsNullOrEmpty(stationname) && stationname.endsWith("水库"))
            stationname.substring(0, stationname.length() - 2);
        Object list1 = skInfoService.getWaterWarnMoniInfo(stationname);
        rltList.add(list1);
        Object list2 = skInfoService.getRiverWarnMoniInfo();
        rltList.add(list2);
        return rltList;
    }

    public static String getDatePoor(Date endDate, Date nowDate) {

        long nd = 1000 * 24 * 60 * 60;//每天毫秒数

        long nh = 1000 * 60 * 60;//每小时毫秒数

        long nm = 1000 * 60;//每分钟毫秒数

        long diff = endDate.getTime() - nowDate.getTime(); // 获得两个时间的毫秒时间差异

        long day = diff / nd;   // 计算差多少天

        long hour = diff % nd / nh; // 计算差多少小时

        long min = diff % nd % nh / nm;  // 计算差多少分钟

        return day * 24 + hour + "";
    }

    /***1
     * 采集时间
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetCollectTimeByType")
    @ResponseBody
    public Object getCollectTimeByType(HttpServletRequest request, Model model) {
        String type = request.getParameter("type");
        return qxInfoService.getCollectTimeByType(type);
    }

    /***1
     * 采集日志
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetCollectLogByTimeNType")
    @ResponseBody
    public Object getCollectLogByTimeNType(HttpServletRequest request, Model model) throws ParseException {
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        String type = request.getParameter("type");
        Date startDate = null;
        Date endDate = null;
        if (!StringUtil.IsNullOrEmpty(start)) {
            startDate=DateTime.parseDateTime(start).toDate();
        }
        if (!StringUtil.IsNullOrEmpty(end)) {
            endDate=DateTime.parseDateTime(end).toDate();
        }
        return qxInfoService.getCollectLogByTimeNType(startDate,endDate,type);
    }
    /***
     * 等值分级
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetContourSettingByType")
    @ResponseBody
    public Object getContourSettingByType(HttpServletRequest request, Model model) {
        String elementType = request.getParameter("elementtype");
        return qxInfoService.getContourSettingByType(elementType);
    }

    /***
     * 雷达图文件
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetDopplerImage")
    @ResponseBody
    public Object getDopplerImage(HttpServletRequest request, Model model) throws ParseException {
        List<doppler> dopplerList=qxInfoService.getDopplerImage1(request);
        return dopplerList;
    }

    /**
     * 干旱检测
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetDroughtCIByTime")
    @ResponseBody
    public Object getDroughtCIByTime(HttpServletRequest request, Model model) throws ParseException {
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        Date startDate = null;
        Date endDate = null;
        if (!StringUtil.IsNullOrEmpty(start)) {
            startDate=DateTime.parseDateTime(start).toDate();
        }
        if (!StringUtil.IsNullOrEmpty(end)) {
            endDate=DateTime.parseDateTime(end).toDate();
        }
        String stationid = request.getParameter("stationid");
        return qxInfoService.getDroughtCIByTime(startDate,endDate,stationid);
    }

    /**
     * 城镇预报
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetCityForecastByTimeNArea")
    @ResponseBody
    public Object getCityForecastByTimeNArea(HttpServletRequest request, Model model) throws ParseException {
        ForecastInfo forecastInfo = new ForecastInfo();
        String date = request.getParameter("datechar");
        Date datechar = null;
        if (!StringUtil.IsNullOrEmpty(date)) {
            datechar = DateTime.parseDateTime(date).toDate();
        }
        forecastInfo.setDatechar(datechar);
        forecastInfo.setTimechar(request.getParameter("timechar"));
        forecastInfo.setCity(request.getParameter("city"));
        forecastInfo.setStationid(request.getParameter("stationid"));

        WebCtrlData wcd = new WebCtrlData();
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        try {
            List<ForecastInfo> fcstList = qxInfoService.getCityForecastByTimeNArea(forecastInfo);
            int count = fcstList.toArray().length;
            for (int i = 0; i < count; i++) {
                String strStationID = fcstList.get(i).getStationid();
                String strCountyName = fcstList.get(i).getStationname();
                String city = fcstList.get(i).getCity();
                String county = fcstList.get(i).getCounty();
                String weather = "";// 天气信息
                String windD = "";// 风向信息
                String windV = "";// 风力信息
                String windD12 = wcd.GetAllFx(fcstList.get(i).getWindd1().toString().replace("-65535", "0").trim());
                String windD24 = wcd.GetAllFx(fcstList.get(i).getWindd2().toString().replace("-65535", "0").trim());
                String windV12 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWind1())));
                String windV24 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWind2())));
                if (windD12.equals(windD24)) {
                    windD += windD12;
                } else {
                    windD += windD12 + "转" + windD24;
                }
                if (windV12.equals(windV24)) {
                    windV += windV12;
                } else {
                    windV += windV12 + "~" + windV24;
                }
                if (fcstList.get(i).getWeather1().toString().trim()
                        .equals(fcstList.get(i).getWeather2().toString().trim())) {
                    weather += wcd.GetWeatherTq(String.format("%02d",
                            Integer.parseInt(fcstList.get(i).getWeather1().toString().trim())));
                } else {
                    weather += wcd
                            .GetWeatherTq(String.format("%02d",
                                    Integer.parseInt(fcstList.get(i).getWeather1().toString().trim())))
                            + "转" + wcd.GetWeatherTq(String.format("%02d",
                            Integer.parseInt(fcstList.get(i).getWeather2().toString().trim())));
                }
                double maxTemp = Double.parseDouble(String.format("%.1f", fcstList.get(i).getMaxtemp()));
                double minTemp = Double.parseDouble(String.format("%.1f", fcstList.get(i).getMintemp()));
                CityFcstInfo fcstInfo = new CityFcstInfo();
                fcstInfo.setStationId(strStationID);
                fcstInfo.setStationName(strCountyName);
                fcstInfo.setMinTemp(minTemp);
                fcstInfo.setMaxTemp(maxTemp);
                fcstInfo.setWindD(windD);
                fcstInfo.setWindV(windV);
                fcstInfo.setWeather(weather);
                fcstInfo.setTime(new DateTime(fcstList.get(i).getDatechar()).toDateString());
                fcstInfo.setCity(city);
                fcstInfo.setCounty(county);
                resultList.add(fcstInfo);
            }
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), false);
        }
        return new ResultObj("查询成功", resultList, false);
    }

    /**
     * 全国城镇报
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetCountryCityForecastByTimeNArea")
    @ResponseBody
    public Object getCountryCityForecastByTimeNArea(HttpServletRequest request, Model model) throws ParseException {
        ForecastInfo forecastInfo = new ForecastInfo();
        String date = request.getParameter("datechar");
        Date datechar = null;
        if (!StringUtil.IsNullOrEmpty(date)) {
            datechar = DateTime.parseDateTime(date).toDate();
        }
        forecastInfo.setDatechar(datechar);
        forecastInfo.setTimechar(request.getParameter("timechar"));
        forecastInfo.setCity(request.getParameter("city"));
        forecastInfo.setStationid(request.getParameter("county"));

        WebCtrlData wcd = new WebCtrlData();
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        try {
            List<ForecastInfo> fcstList = qxInfoService.getCountryCityForecastByTimeNArea(forecastInfo);
            for (int i = 0; i < fcstList.toArray().length; i++) {
                String strStationID = fcstList.get(i).getStationid();
                String strCountyName = fcstList.get(i).getStationname();
                String city = fcstList.get(i).getCity();
                String county = fcstList.get(i).getCounty();
                String weather = "";// 天气信息
                String windD = "";// 风向信息
                String windV = "";// 风力信息
                String windD12 = wcd.GetAllFx(fcstList.get(i).getWindd1().toString().replace("-65535", "0").trim());
                String windD24 = wcd.GetAllFx(fcstList.get(i).getWindd2().toString().replace("-65535", "0").trim());
                String windV12 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWind1())));
                String windV24 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWind2())));
                if (windD12.equals(windD24)) {
                    windD += windD12;
                } else {
                    windD += windD12 + "转" + windD24;
                }
                if (windV12.equals(windV24)) {
                    windV += windV12;
                } else {
                    windV += windV12 + "~" + windV24;
                }
                if (fcstList.get(i).getWeather1().toString().trim()
                        .equals(fcstList.get(i).getWeather2().toString().trim())) {
                    weather += wcd.GetWeatherTq(String.format("%02d",
                            Integer.parseInt(fcstList.get(i).getWeather1().toString().trim())));
                } else {
                    weather += wcd
                            .GetWeatherTq(String.format("%02d",
                                    Integer.parseInt(fcstList.get(i).getWeather1().toString().trim())))
                            + "转" + wcd.GetWeatherTq(String.format("%02d",
                            Integer.parseInt(fcstList.get(i).getWeather2().toString().trim())));
                }
                double maxTemp = Double.parseDouble(String.format("%.1f", fcstList.get(i).getMaxtemp()));
                double minTemp = Double.parseDouble(String.format("%.1f", fcstList.get(i).getMintemp()));
                CityFcstInfo fcstInfo = new CityFcstInfo();
                fcstInfo.setStationId(strStationID);
                fcstInfo.setStationName(strCountyName);
                fcstInfo.setMinTemp(minTemp);
                fcstInfo.setMaxTemp(maxTemp);
                fcstInfo.setWindD(windD);
                fcstInfo.setWindV(windV);
                fcstInfo.setWeather(weather);
                fcstInfo.setTime(new DateTime(fcstList.get(i).getDatechar()).toDateString());
                fcstInfo.setCity(city);
                fcstInfo.setCounty(county);
                resultList.add(fcstInfo);
            }
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), false);
        }
        return new ResultObj("查询成功", resultList, false);
    }

    /**
     * 自动站
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/GetSmallScaleByTimeNArea")
    @ResponseBody
    public Object getSmallScaleByTimeNArea(HttpServletRequest request, Model model) throws ParseException {
        ActualElemQuery elemQuery = new ActualElemQuery();
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        String elements = request.getParameter("elements");
        String[] split = elements.split(",");
        Date startDate = null;
        Date endDate = null;
        if (!StringUtil.IsNullOrEmpty(start)) {
            startDate=DateTime.parseDateTime(start).toDate();
        }
        if (!StringUtil.IsNullOrEmpty(end)) {
            endDate=DateTime.parseDateTime(end).toDate();
        }
        String city = request.getParameter("city");
        String county = request.getParameter("county");

        //要素获取
        elemQuery.setCity(city);
        elemQuery.setCounty(county);
        elemQuery.setStartDate(startDate);
        elemQuery.setEndDate(endDate);
        elemQuery.setElements(Arrays.asList(split));
        return qxInfoService.getSmallScaleByTimeNArea(elemQuery);
    }

    /**
     * 自动站
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/GetSmallScaleByTimeNStationIds")
    @ResponseBody
    public Object getSmallScaleByTimeNStationIds(HttpServletRequest request, Model model) throws ParseException {
        ActualElemQuery elemQuery = new ActualElemQuery();
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        Date startDate = null;
        Date endDate = null;
        if (!StringUtil.IsNullOrEmpty(start)) {
            startDate=DateTime.parseDateTime(start).toDate();
        }
        if (!StringUtil.IsNullOrEmpty(end)) {
            endDate=DateTime.parseDateTime(end).toDate();
        }
        String stations = request.getParameter("stations");
        String elements = request.getParameter("elements");
        String[] split1 = elements.split(",");
        String[] split = stations.split(",");
        elemQuery.setStations(Arrays.asList(split));
        elemQuery.setStartDate(startDate);
        elemQuery.setEndDate(endDate);
        elemQuery.setElements(Arrays.asList(split1));
        return qxInfoService.getSmallScaleByTimeNStationIds(elemQuery);
    }
    /**
     * 闪电定位
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/GetRaidenByTimeNArea")
    @ResponseBody
    public Object getRaidenByTimeNArea(HttpServletRequest request, Model model) throws ParseException {
        //时间区间（observetime）、市（city）、县（county）
        ActualElemQuery elemQuery = new ActualElemQuery();
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        Date startDate = null;
        Date endDate = null;
        if (!StringUtil.IsNullOrEmpty(start)) {
            startDate=DateTime.parseDateTime(start).toDate();
        }
        if (!StringUtil.IsNullOrEmpty(end)) {
            endDate=DateTime.parseDateTime(end).toDate();
        }
        String city = request.getParameter("city");
        String county = request.getParameter("county");
        elemQuery.setStartDate(startDate);
        elemQuery.setEndDate(endDate);
        elemQuery.setCity(city);
        elemQuery.setCounty(county);
        return qxInfoService.getRaidenByTimeNArea(elemQuery);
    }
    /**
     * 闪电定位
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/GetRaidenByTimeNLonLat")
    @ResponseBody
    public Object getRaidenByTimeNLonLat(HttpServletRequest request, Model model) throws ParseException {
        ActualElemQuery elemQuery = new ActualElemQuery();
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        Date startDate = null;
        Date endDate = null;
        if (!StringUtil.IsNullOrEmpty(start)) {
            startDate=DateTime.parseDateTime(start).toDate();
        }
        if (!StringUtil.IsNullOrEmpty(end)) {
            endDate=DateTime.parseDateTime(end).toDate();
        }
        String lon = request.getParameter("lon");
        String lat = request.getParameter("lat");
        if (!StringUtil.IsNullOrEmpty(lon)) {
            elemQuery.setLon(Float.parseFloat(lon));
        }
        if (!StringUtil.IsNullOrEmpty(lat)) {
            elemQuery.setLat(Float.parseFloat(lat));
        }
        elemQuery.setStartDate(startDate);
        elemQuery.setEndDate(endDate);
        return qxInfoService.getRaidenByTimeNLonLat(elemQuery);
    }

    /**
     * 水库水情
     *
     * @param request
     * @param model
     * @return1
     * @throws ParseException
     */
    @RequestMapping("/GetReservoirWaterInfoByTimeNArea")
    @ResponseBody
    public Object getReservoirWaterInfoByTimeNArea(HttpServletRequest request, Model model) throws ParseException {
        reservoirWaterInfo reservoirWaterInfo = new reservoirWaterInfo();
        String city = request.getParameter("city");
        String county = request.getParameter("county");
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        Date startDate = null;
        Date endDate = null;
        if (!StringUtil.IsNullOrEmpty(start)) {
            startDate=DateTime.parseDateTime(start).toDate();
        }
        if (!StringUtil.IsNullOrEmpty(end)) {
            endDate=DateTime.parseDateTime(end).toDate();
        }
        reservoirWaterInfo.setCity(city);
        reservoirWaterInfo.setCounty(county);
        return qxInfoService.getReservoirWaterInfoByTimeNArea(startDate,endDate,reservoirWaterInfo);
    }

    /**
     * 水库水情
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/GetReservoirWaterInfoByTimeNStationIds")
    @ResponseBody
    public Object getReservoirWaterInfoByTimeNStationIds(HttpServletRequest request, Model model) throws ParseException {
        ActualElemQuery actualElemQuery = new ActualElemQuery();
        String stations = request.getParameter("stations");
        String[] split = stations.split(",");
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        Date startDate = null;
        Date endDate = null;
        if (!StringUtil.IsNullOrEmpty(start)) {
            startDate=DateTime.parseDateTime(start).toDate();
        }
        if (!StringUtil.IsNullOrEmpty(end)) {
            endDate=DateTime.parseDateTime(end).toDate();
        }
        actualElemQuery.setStartDate(startDate);
        actualElemQuery.setEndDate(endDate);
        actualElemQuery.setStations(Arrays.asList(split));
        return qxInfoService.getReservoirWaterInfoByTimeNStationIds(actualElemQuery);
    }
    /**
     * 河道水情
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/GetRiverWaterInfoByTimeNArea")
    @ResponseBody
    public Object getRiverWaterInfoByTimeNArea(HttpServletRequest request, Model model) throws ParseException {
        //间区间（latestobservetime）、市县（addvcd）
        String addvcd = request.getParameter("addvcd");
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        Date startDate = null;
        Date endDate = null;
        if (!StringUtil.IsNullOrEmpty(start)) {
            startDate=DateTime.parseDateTime(start).toDate();
        }
        if (!StringUtil.IsNullOrEmpty(end)) {
            endDate=DateTime.parseDateTime(end).toDate();
        }
        return qxInfoService.getRiverWaterInfoByTimeNArea(startDate,endDate,addvcd);
    }

    /**
     * 河道水情
     * 1
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/GetRiverWaterInfoByTimeNStationIds")
    @ResponseBody
    public Object getRiverWaterInfoByTimeNStationIds(HttpServletRequest request, Model model) throws ParseException {
        String stations = request.getParameter("stations");
        String[] split = stations.split(",");
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        Date startDate = null;
        Date endDate = null;
        if (!StringUtil.IsNullOrEmpty(start)) {
            startDate=DateTime.parseDateTime(start).toDate();
        }
        if (!StringUtil.IsNullOrEmpty(end)) {
            endDate=DateTime.parseDateTime(end).toDate();
        }
        return qxInfoService.getRiverWaterInfoByTimeNStationIds(startDate,endDate,split);
    }

    /**
     * 山洪水情
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/GetWaterRainInfoByTimeNArea")
    @ResponseBody
    public Object getWaterRainInfoByTimeNArea(HttpServletRequest request, Model model) throws ParseException {
        String addvcd = request.getParameter("addvcd");
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        Date startDate = null;
        Date endDate = null;
        if (!StringUtil.IsNullOrEmpty(start)) {
            startDate=DateTime.parseDateTime(start).toDate();
        }
        if (!StringUtil.IsNullOrEmpty(end)) {
            endDate=DateTime.parseDateTime(end).toDate();
        }
        return qxInfoService.getWaterRainInfoByTimeNArea(startDate,endDate,addvcd);
    }
    /**
     * 山洪水情
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/GetWaterRainInfoByTimeNStationIds")
    @ResponseBody
    public Object getWaterRainInfoByTimeNStationIds(HttpServletRequest request, Model model) throws ParseException {
        String stations = request.getParameter("stcd");
        String[] split = stations.split(",");
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        Date startDate = null;
        Date endDate = null;
        if (!StringUtil.IsNullOrEmpty(start)) {
            startDate=DateTime.parseDateTime(start).toDate();
        }
        if (!StringUtil.IsNullOrEmpty(end)) {
            endDate=DateTime.parseDateTime(end).toDate();
        }
        return qxInfoService.getWaterRainInfoByTimeNStationIds(startDate,endDate,split);
    }

    /**
     * 土壤湿度
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/GetSoilHumidityByTimeNStationids")
    @ResponseBody
    public Object getSoilHumidityByTimeNStationids(HttpServletRequest request, Model model) throws ParseException {
        String stationid = request.getParameter("stationid");
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        Date startDate = null;
        Date endDate = null;
        if (!StringUtil.IsNullOrEmpty(start)) {
            startDate=DateTime.parseDateTime(start).toDate();
        }
        if (!StringUtil.IsNullOrEmpty(end)) {
            endDate=DateTime.parseDateTime(end).toDate();
        }
        return qxInfoService.getSoilHumidityByTimeNStationids(startDate,endDate, stationid);
    }


    @RequestMapping("/GetHistoryByElement")
    @ResponseBody
    public Object getHistoryByElement(HttpServletRequest request, Model model) throws ParseException {
        String element = request.getParameter("element");
        String date = request.getParameter("date");
        String advname = request.getParameter("advcode");
        String county = request.getParameter("advname");
        //String stationId = configService.getStationId(county);
        String result = "";
        String county1 = "";
        switch (county){
            case "伊犁州直":
                county1 = "'伊宁市','察布查尔锡伯自治县','奎屯市','霍尔果斯市','伊宁县','巩留县','霍城县','新源县','昭苏县','特克斯县','尼勒克县'";
                break;
            case "伊犁河谷":
                county1 = "'伊宁市','察布查尔锡伯自治县','霍尔果斯市','伊宁县','巩留县','霍城县','新源县','昭苏县','特克斯县','尼勒克县'";
                break;
            case "察县":
                county1 = "'察布查尔锡伯自治县'";
                break;
            case "伊宁市":
                county1 = "'伊宁市'";
                break;
            case "奎屯市":
                county1 = "'奎屯市'";
                break;
            case "霍尔果斯市":
                county1 = "'霍尔果斯市'";
                break;
            case "伊宁县":
                county1 = "'伊宁县'";
                break;
            case "巩留县":
                county1 = "'巩留县'";
                break;
            case "霍城县":
                county1 = "'霍城县'";
                break;
            case "新源县":
                county1 = "'新源县'";
                break;
            case "昭苏县":
                county1 = "'昭苏县'";
                break;
            case "特克斯县":
                county1 = "'特克斯县'";
                break;
            case "尼勒克县":
                county1 = "'尼勒克县'";
                break;
            default:
                return null;
        }
        String stationId = "";
        switch (county){
            case "伊犁州直":
                stationId = "51431";
                break;
            case "伊犁河谷":
                stationId = "51431";
                break;
            case "伊宁市":
                stationId = "51431";
                break;
            case "奎屯市":
                stationId = "Y5169";
                break;
            case "霍尔果斯市":
                stationId = "51328";
                break;
            case "察县":
                stationId = "51430";
                break;
            case "伊宁县":
                stationId = "51434";
                break;
            case "巩留县":
                stationId = "51435";
                break;
            case "霍城县":
                stationId = "51329";
                break;
            case "新源县":
                stationId = "51436";
                break;
            case "昭苏县":
                stationId = "51523";
                break;
            case "特克斯县":
                stationId = "51438";
                break;
            case "尼勒克县":
                stationId = "51440";
                break;
            default:
                return null;
        }
        try {
            StringBuilder sql = new StringBuilder();
            sql.append("select stationid,longitude,latitude,stationname ")
                    .append("from smallscale_station ")
                    .append("where county IN (" + county1 + ")");
            List<Map<String, Object>> res = comDisplayService.getStationInfo(sql.toString());
            // 使用 StringJoiner 来连接结果
            StringJoiner joiner = new StringJoiner(",");

            // 遍历 res 列表，提取每个 stationid，并在添加到 joiner 时加上单引号
            for (Map<String, Object> station : res) {
                String stationId1 = (String) station.get("stationid");
                joiner.add("'" + stationId1 + "'");  // 在每个 stationid 前后加上单引号
            }

            // 最终结果就是你想要的字符串
            result = joiner.toString();
        }catch (Exception e){
            return "查询失败";
        }

        return qxInfoService.getHistoryByElement(element,date,county,advname,result);


    }
    @GetMapping("/getQiHouByTime")
    @ResponseBody
    public Results getQiHouByTime(HttpServletRequest request, Model model) {
        try{
            String county = request.getParameter("advname");
            String county1 = "";
            switch (county){
                case "伊犁州直":
                    county1 ="伊宁市";
                    break;
                case "伊犁河谷":
                    county1 ="伊宁市";
                    break;
                case "察县":
                    county1 = "察布查尔锡伯自治县";
                    break;
                case "伊宁市":
                    county1 = "伊宁市";
                    break;
                case "奎屯市":
                    county1 = "奎屯市";
                    break;
                case "霍尔果斯市":
                    county1 = "霍尔果斯市";
                    break;
                case "伊宁县":
                    county1 = "伊宁县";
                    break;
                case "巩留县":
                    county1 = "巩留县";
                    break;
                case "霍城县":
                    county1 = "霍城县";
                    break;
                case "新源县":
                    county1 = "新源县";
                    break;
                case "昭苏县":
                    county1 = "昭苏县";
                    break;
                case "特克斯县":
                    county1 = "特克斯县";
                    break;
                case "尼勒克县":
                    county1 = "尼勒克县";
                    break;
                default:
                    return null;

            }
            HashMap<String, Map<String, Object>> map1 = new HashMap<>();
            HashMap<String, Object> monthList = new HashMap<>();
            StringBuilder sql = new StringBuilder();
            sql.append("select stationid,longitude,latitude,stationname ")
                    .append("from smallscale_station ")
                    .append("where county = '" + county1 + "'");
            List<Map<String, Object>> res = comDisplayService.getStationInfo(sql.toString());
            System.out.println("res: " + res);
            // 使用 StringJoiner 来连接结果
            StringJoiner joiner = new StringJoiner(",");

            // 遍历 res 列表，提取每个 stationid，并在添加到 joiner 时加上单引号
            for (Map<String, Object> station : res) {
                String stationId1 = (String) station.get("stationid");
                joiner.add("'" + stationId1 + "'");  // 在每个 stationid 前后加上单引号
            }

            // 最终结果就是你想要的字符串
            String result = joiner.toString();
            List<sum_rain_day_data> qiHouByTemp2 = qxInfoService.getQiHouByTemp2(result);//平均气温
// 如果返回的数据为空，创建一个包含默认值的 MaxTemperatureData 对象
            if (qiHouByTemp2 == null || qiHouByTemp2.isEmpty()) {
                sum_rain_day_data defaultData = new sum_rain_day_data(0.0, "暂无数据", 0);
                monthList.put("averageTemperature", defaultData);//平均气温
            }else {
                monthList.put("averageTemperature", qiHouByTemp2.get(0));//平均气温
            }
            List<sum_rain_day_data> qiHouByTemp = qxInfoService.getQiHouByTemp(result);//最高温
            if (qiHouByTemp == null || qiHouByTemp.isEmpty()) {
                sum_rain_day_data defaultData = new sum_rain_day_data(0.0, "暂无数据", 0);
                monthList.put("minTemperature", defaultData);//平均气温
            }else {
                monthList.put("minTemperature", qiHouByTemp.get(0));//平均气温
            }
            List<sum_rain_day_data> qiHouByRain = qxInfoService.getQiHouByRain(result);//最低温
            if (qiHouByRain == null || qiHouByRain.isEmpty()) {
                sum_rain_day_data defaultData = new sum_rain_day_data(0.0, "暂无数据", 0);
                monthList.put("maxTemperature",defaultData);
            }else{
                monthList.put("maxTemperature", qiHouByRain.get(0));
            }
            List<sum_rain_day_data> qiHouByRain1 = qxInfoService.getQiHouByRain11(result);
            if (qiHouByRain1 == null || qiHouByRain1.isEmpty()) {
                sum_rain_day_data defaultData = new sum_rain_day_data(0.0, "暂无数据", 0);
                monthList.put("cumulativeRainfall",defaultData);
            }else{
                monthList.put("cumulativeRainfall", qiHouByRain1.get(0));
            }
            List<sum_rain_day_data> qiHouByRain11 = qxInfoService.getQiHouByRain1(result);
            if (qiHouByRain11 == null || qiHouByRain11.isEmpty()) {
                sum_rain_day_data defaultData = new sum_rain_day_data(0.0, "暂无数据", 0);
                monthList.put("maxDailyRainfall",defaultData);
            }else{
                monthList.put("maxDailyRainfall", qiHouByRain11.get(0));
            }
            List<sum_rain_day_data> qiHouByRain2 = qxInfoService.getQiHouByRain2(result);
            if (qiHouByRain2 == null || qiHouByRain2.isEmpty()) {
                sum_rain_day_data defaultData = new sum_rain_day_data(0.0, "暂无数据", 0);
                monthList.put("maxHourlyRainfall",defaultData);
            }else{
                monthList.put("maxHourlyRainfall", qiHouByRain2.get(0));
            }
            HashMap<String, Object> yearList = new HashMap<>();
            List<sum_rain_day_data> qiHouByTemp6 = qxInfoService.getQiHouByTemp6(result);//年平均气温
            if (qiHouByTemp6 == null || qiHouByTemp6.isEmpty()) {
                sum_rain_day_data defaultData = new sum_rain_day_data(0.0, "暂无数据", 0);
                yearList.put("averageTemperature",defaultData);//年平均气温
            }else{
                yearList.put("averageTemperature", qiHouByTemp6.get(0));//年平均气温
            }
            List<sum_rain_day_data> qiHouByTemp7 = qxInfoService.getQiHouByTemp7(result);//年平最高温
            if (qiHouByTemp7 == null || qiHouByTemp7.isEmpty()) {
                sum_rain_day_data defaultData = new sum_rain_day_data(0.0, "暂无数据", 0);
                yearList.put("maxTemperature",defaultData);//年平均气温
            }else{
                yearList.put("maxTemperature", qiHouByTemp7.get(0));//年平均气温
            }
            List<sum_rain_day_data> qiHouByTemp8 = qxInfoService.getQiHouByTemp8(result);
            if (qiHouByTemp8 == null || qiHouByTemp8.isEmpty()) {
                sum_rain_day_data defaultData = new sum_rain_day_data(0.0, "暂无数据", 0);
                yearList.put("minTemperature",defaultData);//年平最低温
            }else{
                yearList.put("minTemperature", qiHouByTemp8.get(0));//年平最低温
            }
            List<sum_rain_day_data> qiHouByTemp9 = qxInfoService.getQiHouByTemp9(result);
            if (qiHouByTemp9 == null || qiHouByTemp9.isEmpty()) {
                sum_rain_day_data defaultData = new sum_rain_day_data(0.0, "暂无数据", 0);
                yearList.put("cumulativeRainfall",defaultData);//年平累计雨量
            }else{
                yearList.put("cumulativeRainfall", qiHouByTemp9.get(0));//年平累计雨量
            }

            List<sum_rain_day_data> qiHouByTemp10 = qxInfoService.getQiHouByTemp10(result);//年平最大日雨量
            if (qiHouByTemp10 == null || qiHouByTemp10.isEmpty()) {
                sum_rain_day_data defaultData = new sum_rain_day_data(0.0, "暂无数据", 0);
                yearList.put("maxDailyRainfall",defaultData);
            }else{
                yearList.put("maxDailyRainfall", qiHouByTemp10.get(0));
            }
            List<sum_rain_day_data> qiHouByTemp11 = qxInfoService.getQiHouByTemp11(result);//年平最大小时雨量
            if (qiHouByTemp11 == null || qiHouByTemp11.isEmpty()) {
                sum_rain_day_data defaultData = new sum_rain_day_data(0.0, "暂无数据", 0);
                yearList.put("maxHourlyRainfall",defaultData);
            }else{
                yearList.put("maxHourlyRainfall", qiHouByTemp11.get(0));
            }


// 将数据添加到最终的 Map 中
            map1.put("summary", monthList);
            map1.put("yearToDate", yearList);

// 返回结果
            return Results.success("查询数据成功", 1, map1);


        }catch (Exception e){
            return Results.fail(e.getMessage());
        }
    }

    //获取月降雨量、平均温
    @GetMapping("/getRainByMonth")
    @ResponseBody
    public Object getRainByMonth(HttpServletRequest request, Model model) {

        String county = request.getParameter("advname");
        int month = Integer.parseInt(request.getParameter("month"));
        //String stationId = configService.getStationId(county);
        String stationId = "";
        switch (county){
            case "伊犁州直":
                stationId = "51431";
                break;
            case "伊犁河谷":
                stationId = "51431";
                break;
            case "伊宁市":
                stationId = "51431";
                break;
            case "奎屯市":
                stationId = "Y5169";
                break;
            case "霍尔果斯市":
                stationId = "51328";
                break;
            case "察县":
                stationId = "51430";
                break;
            case "伊宁县":
                stationId = "51434";
                break;
            case "巩留县":
                stationId = "51435";
                break;
            case "霍城县":
                stationId = "51329";
                break;
            case "新源县":
                stationId = "51436";
                break;
            case "昭苏县":
                stationId = "51523";
                break;
            case "特克斯县":
                stationId = "51438";
                break;
            case "尼勒克县":
                stationId = "51440";
                break;
            default:
                return null;
        }
        try{
            HashMap<String, Map<String, Object>> map1 = new HashMap<>();
            HashMap<String, Object> monthList = new HashMap<>();
            monthList.put("Rain", qxInfoService.getRainByMonth(month,stationId));//平均气温
            monthList.put("Temp",qxInfoService.getTempByMonth(month,stationId));//累计雨量
            monthList.put("Wind",qxInfoService.getWindByMonth(month,stationId));//风速
            map1.put("month",monthList);

            return map1;


        }catch (Exception e){
            return Results.fail(e.getMessage());
        }
    }

    /**
     * 日历史数据
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/GetHistoryDayDataByTimeNStationIds")
    @ResponseBody
    public Object getHistoryDayDataByTimeNStationIds(HttpServletRequest request, Model model) throws ParseException {
        //要素、时间区间、站号
        String stationid = request.getParameter("stationid");
        String element = request.getParameter("element");
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        Date startDate = null;
        Date endDate = null;
        if (!StringUtil.IsNullOrEmpty(start)) {
            startDate=DateTime.parseDateTime(start).toDate();
        }
        if (!StringUtil.IsNullOrEmpty(end)) {
            endDate=DateTime.parseDateTime(end).toDate();
        }
        return qxInfoService.getHistoryDayDataByTimeNStationIds(start,end, stationid,element);
    }

    /**
     * 月历史数据
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/GetHistoryMonthDataByTimeNStationIds")
    @ResponseBody
    public Object getHistoryMonthDataByTimeNStationIds(HttpServletRequest request, Model model) throws ParseException {
        //要素、时间区间、站号
        String stationid = request.getParameter("stationid");
        String element = request.getParameter("element");
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        return qxInfoService.getHistoryMonthDataByTimeNStationIds(start,end, stationid,element);
    }
    /**
     * 年历史数据
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/GetHistoryYearDataByTimeNStationIds")
    @ResponseBody
    public Object getHistoryYearDataByTimeNStationIds(HttpServletRequest request, Model model) throws ParseException {
        //要素、时间区间、站号
        String stationid = request.getParameter("stationid");
        String element = request.getParameter("element");
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        return qxInfoService.getHistoryYearDataByTimeNStationIds(start,end, stationid,element);
    }

    /**
     * 乡镇预报
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetTownForecastByTimeNArea")
    @ResponseBody
    public Object GetTownForecastByTimeNArea(HttpServletRequest request, Model model) throws ParseException {
        township_forecast townshipForecast = new township_forecast();
        String date = request.getParameter("datechar");
        Date datechar = null;
        if (!StringUtil.IsNullOrEmpty(date)) {
            datechar = DateTime.parseDateTime(date).toDate();
        }
        townshipForecast.setDatechar(datechar);
        townshipForecast.setTimechar(request.getParameter("timechar"));
        townshipForecast.setCity(request.getParameter("city"));
        townshipForecast.setAreaname(request.getParameter("areaname"));

        WebCtrlData wcd = new WebCtrlData();
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        try {
            List<township_forecast> fcstList = qxInfoService.getTownForecastByTimeNArea(townshipForecast);
            int count = fcstList.toArray().length;
            for (int i = 0; i < count; i++) {
                String strStationID = fcstList.get(i).getStationid();
                String strCountyName = fcstList.get(i).getStationname();
                String city = fcstList.get(i).getCity();
                String areaname = fcstList.get(i).getAreaname();
                String windD = wcd.GetAllFx(fcstList.get(i).getWindd().toString().replace("-65535", "0").trim());
                String windV = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWinds())));
                String weather = wcd.GetWeatherTq(String.format("%02d",
                        Integer.parseInt(fcstList.get(i).getWeather1().toString().trim())));
                double maxTemp = Double.parseDouble(String.format("%.1f", fcstList.get(i).getMaxtemp()));
                double minTemp = Double.parseDouble(String.format("%.1f", fcstList.get(i).getMintemp()));
                CityFcstInfo fcstInfo = new CityFcstInfo();
                fcstInfo.setStationId(strStationID);
                fcstInfo.setStationName(strCountyName);
                fcstInfo.setMinTemp(minTemp);
                fcstInfo.setMaxTemp(maxTemp);
                fcstInfo.setWindD(windD);
                fcstInfo.setWindV(windV);
                fcstInfo.setWeather(weather);
                fcstInfo.setTime(new DateTime(fcstList.get(i).getDatechar()).toDateString());
                fcstInfo.setCity(city);
                fcstInfo.setAreaname(areaname);
                resultList.add(fcstInfo);
            }
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), false);
        }
        return new ResultObj("查询成功", resultList, false);
    }

    /**
     * 乡镇预报
     *
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/GetTownForecastByTimeNStationids")
    @ResponseBody
    public Object getTownForecastByTimeNStationids(HttpServletRequest request, Model model) throws ParseException {
        township_forecast townshipForecast = new township_forecast();
        String date = request.getParameter("datechar");
        Date datechar = null;
        if (!StringUtil.IsNullOrEmpty(date)) {
            datechar = DateTime.parseDateTime(date).toDate();
        }
        townshipForecast.setDatechar(datechar);
        townshipForecast.setTimechar(request.getParameter("timechar"));
        townshipForecast.setCity(request.getParameter("stationid"));

        WebCtrlData wcd = new WebCtrlData();
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        try {
            List<township_forecast> fcstList = qxInfoService.getTownForecastByTimeNStationids(townshipForecast);
            int count = fcstList.toArray().length;
            for (int i = 0; i < count; i++) {
                String strStationID = fcstList.get(i).getStationid();
                String strCountyName = fcstList.get(i).getStationname();
                String city = fcstList.get(i).getCity();
                String areaname = fcstList.get(i).getAreaname();
                String windD = wcd.GetAllFx(fcstList.get(i).getWindd().toString().replace("-65535", "0").trim());
                String windV = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWinds())));
                String weather = wcd.GetWeatherTq(String.format("%02d",
                        Integer.parseInt(fcstList.get(i).getWeather1().toString().trim())));
                double maxTemp = Double.parseDouble(String.format("%.1f", fcstList.get(i).getMaxtemp()));
                double minTemp = Double.parseDouble(String.format("%.1f", fcstList.get(i).getMintemp()));
                CityFcstInfo fcstInfo = new CityFcstInfo();
                fcstInfo.setStationId(strStationID);
                fcstInfo.setStationName(strCountyName);
                fcstInfo.setMinTemp(minTemp);
                fcstInfo.setMaxTemp(maxTemp);
                fcstInfo.setWindD(windD);
                fcstInfo.setWindV(windV);
                fcstInfo.setWeather(weather);
                fcstInfo.setTime(new DateTime(fcstList.get(i).getDatechar()).toDateString());
                fcstInfo.setCity(city);
                fcstInfo.setAreaname(areaname);
                resultList.add(fcstInfo);
            }
        } catch (Exception e) {
            return new ResultObj("查询失败", e.getMessage(), false);
        }
        return new ResultObj("查询成功", resultList, false);
    }

    /**
     * 预警信号
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/GetWarnSignalByTimeNArea")
    @ResponseBody
    public Object getWarnSignalByTimeNArea(HttpServletRequest request, Model model) throws ParseException {
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        Date startDate = null;
        Date endDate = null;
        if (!StringUtil.IsNullOrEmpty(start)) {
            startDate=DateTime.parseDateTime(start).toDate();
        }
        if (!StringUtil.IsNullOrEmpty(end)) {
            endDate=DateTime.parseDateTime(end).toDate();
        }
        String area = request.getParameter("area");
        String city = request.getParameter("city");
        return qxInfoService.getWarnSignalByTimeNArea(startDate,endDate, area, city);
    }
    /**
     * 组网雷达
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/GetUnionRadarByTimeNType")
    @ResponseBody
    public Object getUnionRadarByTimeNType(HttpServletRequest request, Model model) throws ParseException {
        String date = request.getParameter("datechar");
        Date datechar = null;
        if (!StringUtil.IsNullOrEmpty(date)) {
            datechar = DateTime.parseDateTime(date).toDate();
        }
        String timechar = request.getParameter("timechar");
        String ldtype = request.getParameter("ldtype");
        return qxInfoService.getUnionRadarByTimeNType(datechar, timechar, ldtype);
    }
    /**
     * 云图文件
     *
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/GetFYImages")
    @ResponseBody
    public Object getFYImages(HttpServletRequest request, Model model) throws ParseException {
        List<satellitenephoram> satellitenephorams = qxInfoService.getFYImages1(request);
        return satellitenephorams;
    }

    /**
     * 指数气象
     * @param request
     * @param model
     * @return
     * @throws ParseException
     */
    @RequestMapping("/GetZhishu")
    @ResponseBody
    public Object getZhishu(HttpServletRequest request, Model model) throws ParseException {
        zhiShu zhiShu = new zhiShu();
        String date = request.getParameter("datechar");
        Date datechar = null;
        if (!StringUtil.IsNullOrEmpty(date)) {
            datechar = DateTime.parseDateTime(date).toDate();
        }
        String timechar = request.getParameter("timechar");
        String cityid = request.getParameter("cityid");
        String cityname = request.getParameter("cityname");
        zhiShu.setDatechar(datechar);
        zhiShu.setTimechar(timechar);
        zhiShu.setCityid(cityid);
        zhiShu.setCityname(cityname);
        return qxInfoService.getZhishu(zhiShu);
    }

    @RequestMapping("/tempQuery")
    @ResponseBody
    public Object tempQuery(HttpServletRequest request) {
        List<msgmediumsmallscale> list = qxInfoService.tempQuery();
        String temp = "";
        if (list != null && list.size() > 0) {
            String xValue = "[";
            String yValue = "[";
            for (msgmediumsmallscale r : list) {
                xValue += "'" + new DateTime(r.getObservtime()).toDateTimeString("HH") + "',";
                yValue += r.getMaxtemp() + ",";
            }
            xValue = xValue.substring(0, xValue.length() - 1) + "]";
            yValue = yValue.substring(0, yValue.length() - 1) + "]";
            yValue = "[{name:'气温',data:" + yValue + "}]";
            temp = xValue + "|" + yValue;
        }
        return temp;
    }
    /**
     * 初始化常规产品类型
     *
     * @param
     * @return
     * @author ymf
     * @date 2019/12/23
     **/
    @RequestMapping("/InitProType")
    @ResponseBody
    public Object InitProType(HttpServletRequest request) {
        List<job_model> list = qxInfoService.InitProType();
        String result = "[";
        if (list != null && list.size() > 0) {
            String temp = "";
            for (int i = 0; i < list.size(); i++) {
                job_model ts = list.get(i);
                if (i == 0) {
                    temp += "{";
                    temp += "\"type\":\"" + ts.getOnetype() + ";" + ts.getTwotype() + "\",";
                } else {
                    if (temp.contains(ts.getOnetype())) {
                        temp = temp.replace("\",",";") + ts.getTwotype() + "\",";
                    } else {
                        temp = temp.substring(0, temp.length() - 1) + "},";
                        result += temp;
                        temp = "{";
                        temp += "\"type\":\"" + ts.getOnetype() + ";" + ts.getTwotype() + "\",";
                        if (i == list.size() - 1) {
                            temp = temp.substring(0, temp.length() - 1) + ",";
                            result += temp;
                        }
                    }
                }
            }
            temp = temp.substring(0, temp.length() - 1) + "},";
            result += temp;
            result = result.substring(0, result.length() - 1) + "]";
        }
        return result;
    }

}
